如何制作`哪里没有'的情况?

War*_*ock 8 javascript underscore.js

我需要在哪里,但没有案例.例如,我想找一些没有名字"莎士比亚"的剧本:

_.where(listOfPlays, {author: !"Shakespeare", year: 1611});
                              ^^^^^^^^^^^^^
                            NOT Shakespeare
Run Code Online (Sandbox Code Playgroud)

我怎么能这样做underscore

jgi*_*ich 10

_.filter(listOfPlays, function(play) {
    return play.author !== 'Shakespeare' && play.year === 1611;
});
Run Code Online (Sandbox Code Playgroud)

http://underscorejs.org/#filter

where只不过是一个方便的包装filter:

// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
    return _.filter(obj, _.matches(attrs));
};
Run Code Online (Sandbox Code Playgroud)

https://github.com/jashkenas/underscore/blob/a6c4041​​70d37aae4f499efb185d610e098d92e47/underscore.js#L249

  • 我认为,拥有`_.not()`包装器也是有用的.例如,`_.not(listOfPlays,{author:"Shakespeare"})`. (2认同)

the*_*eye 7

你可以自己做_.where这个"不在哪里"的版本

_.mixin({
    "notWhere": function(obj, attrs) {
        return _.filter(obj, _.negate(_.matches(attrs)));
    }
});
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样写你的代码

_.chain(listOfPlays)
    .where({
        year: 1611
    })
    .notWhere({
        author: 'Shakespeare'
    })
    .value();
Run Code Online (Sandbox Code Playgroud)

注意: _.negate仅适用于v1.7.0.因此,如果您使用的是以前的版本_,则可能需要执行此类操作

_.mixin({
    "notWhere": function(obj, attrs) {
        var matcherFunction = _.matches(attrs);
        return _.filter(obj, function(currentObject) {
            return !matcherFunction(currentObject);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)