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)
你可以自己做_.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)
归档时间: |
|
查看次数: |
2202 次 |
最近记录: |