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
underscore contains (_.contains) on object types
提问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
contains
requires 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 where
or findWhere
.
但是,您可以使用where
或findWhere
。
if (_.findWhere(indexes, {'id':1, 'name': 'jake'})) {
findWhere
is new in Underscore 1.4.4
so 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");
}