javascript 下划线包含 (_.contains) 对象类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15869648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:23:06  来源:igfitidea点击:

underscore contains (_.contains) on object types

javascriptunderscore.js

提问by Crystal

I'm just getting started with Javascript and using the Underscore library. I see they have all sorts of utility function, like _.contains. Is there a way to make this work on objects?

我刚刚开始使用 Javascript 并使用 Underscore 库。我看到他们有各种各样的效用函数,比如 _.contains。有没有办法在对象上进行这项工作?

var indexes = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'},  {'id': 9, 'name': 'nick'}, {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'} ];

if (_.contains(indexes, {'id':1, 'name': 'jake'})) {
    console.log("contains");
}

Most of the examples they show have simple arrays with strings or numbers in them. I was wondering what I can do to use their utility functions like _.contains for objects. Thanks.

他们展示的大多数示例都有简单的数组,其中包含字符串或数字。我想知道我可以做些什么来使用他们的实用函数,比如 _.contains 用于对象。谢谢。

回答by loganfsmyth

containsrequires the values to be comparable with ===which will not work with different instances of objects.

contains要求这些值具有可比性,===这不适用于不同的对象实例。

For instance it would work if you passed the exact object you are searching for, which isn't very useful.

例如,如果您传递了您正在搜索的确切对象,它就会起作用,这不是很有用。

if (_.contains(indexes, indexes[0])) {

You can however use whereor findWhere.

但是,您可以使用wherefindWhere

if (_.findWhere(indexes, {'id':1, 'name': 'jake'})) {

findWhereis new in Underscore 1.4.4so if you do not have it, you can use where.

findWhere在 Underscore 中是新的,1.4.4所以如果你没有它,你可以使用where.

if (_.where(indexes, {'id':1, 'name': 'jake'}).length > 0) {

回答by mike

You would actually want to use _.wherefor this.

您实际上想为此使用_.where

var indexes = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'},  {'id': 9, 'name': 'nick'}, {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'} ];

if (_.where(indexes, {'id':1, 'name': 'jake'}).length) {
    console.log("contains");
}