Javascript 如何制作“where not”案例?

Javascript 如何制作“where not”案例?,javascript,underscore.js,Javascript,Underscore.js,我需要where,但不需要案例。例如,我想找到没有名字“莎士比亚”的戏剧: 如何使用下划线?尝试以下方法: _.filter(listOfPlays,function(i){ return i['author']!='Shakespeare' && i['year']==1611; }); 其中不过是过滤器周围的一个方便的包装器: // Convenience version of a common use case of `filter`: selecting on

我需要where,但不需要案例。例如,我想找到没有名字“莎士比亚”的戏剧:

如何使用
下划线

尝试以下方法:

_.filter(listOfPlays,function(i){
    return i['author']!='Shakespeare' && i['year']==1611;
});

其中
不过是
过滤器周围的一个方便的包装器

// 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));
};

您可以自己制作
\uwhere的“非何处”版本

_.mixin({
    "notWhere": function(obj, attrs) {
        return _.filter(obj, _.negate(_.matches(attrs)));
    }
});
_.chain(listOfPlays)
    .where({
        year: 1611
    })
    .notWhere({
        author: 'Shakespeare'
    })
    .value();
_.mixin({
    "notWhere": function(obj, attrs) {
        var matcherFunction = _.matches(attrs);
        return _.filter(obj, function(currentObject) {
            return !matcherFunction(currentObject);
        });
    }
});
然后你可以这样写你的代码

_.mixin({
    "notWhere": function(obj, attrs) {
        return _.filter(obj, _.negate(_.matches(attrs)));
    }
});
_.chain(listOfPlays)
    .where({
        year: 1611
    })
    .notWhere({
        author: 'Shakespeare'
    })
    .value();
_.mixin({
    "notWhere": function(obj, attrs) {
        var matcherFunction = _.matches(attrs);
        return _.filter(obj, function(currentObject) {
            return !matcherFunction(currentObject);
        });
    }
});
注意:仅适用于v1.7.0。因此,如果您使用的是以前版本的
,您可能需要执行类似的操作

_.mixin({
    "notWhere": function(obj, attrs) {
        return _.filter(obj, _.negate(_.matches(attrs)));
    }
});
_.chain(listOfPlays)
    .where({
        year: 1611
    })
    .notWhere({
        author: 'Shakespeare'
    })
    .value();
_.mixin({
    "notWhere": function(obj, attrs) {
        var matcherFunction = _.matches(attrs);
        return _.filter(obj, function(currentObject) {
            return !matcherFunction(currentObject);
        });
    }
});

有很多正确的答案,但从技术上讲,OP只是询问否定。您还可以使用reject,它本质上与filter相反。要达到1611年而非莎士比亚的复合条件:

_.where(listOfPlays, {author: !"Shakespeare", year: 1611});
                              ^^^^^^^^^^^^^
                            NOT Shakespeare
_.reject(_.filter(listOfPlays, function(play){
    return play.year === 1611
}), function(play) {
  return play.author === 'Shakespeare';
});

我认为,同样有
\uuu0.not()
包装器也是有用的。例如,
。.not(listOfPlays,{author:“Shakespeare”})
。是的,这会很酷!非常感谢。请注意,最好将函数命名为
not()
@Warlock我们已经调用了一个函数,因此
not
negate
可能会让人困惑…@Warlock但是请记住,
\u.negate
仅在v1.7.0中可用