如何使用 underscore.js 在 javascript 数组中找到给定的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21524371/
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 21:06:00  来源:igfitidea点击:

How can I find a given value exists in javascript array using underscore.js?

javascriptangularjsunderscore.jsjavascript-framework

提问by prince

I want to know whether the given value exists in javascript array or not.

我想知道给定的值是否存在于 javascript 数组中。

Here is my case,

这是我的情况,

var array = [{'id': 1, 'name': 'xxx'},
         {'id': 2, 'name': 'yyy'},
         {'id': 3, 'name': 'zzz'}];

 var searchValue = {'id': 1, 'name': 'xxx'};

I tried the following,

我尝试了以下,

var exists = _.where(array, {name: 'xxx'});

It return the obj {'id': 1, 'name': 'xxx'}. It works as expect.

它返回 obj {'id': 1, 'name': 'xxx'}。它按预期工作。

Here I need to check exists.length > 0to find whether it exists or not

这里我需要检查exists.length > 0一下它是否存在

But is there any other function of get the same.

但是有没有其他功能可以得到相同的。

Since if the function return trueif exists and falseif not, It would be better.

因为如果函数返回true如果存在,false如果不存在,那就更好了。

回答by phtrivier

It's the same idea, but would this do the trick ?

这是相同的想法,但这会成功吗?

return !!_.findWhere(array, {name : 'xxx'});

Otherwise (but slighly longer)

否则(但稍长)

return _.some(array, function (item) {
   return (item.name === "xxx");
});

Also, note that _.where and _.findWhere seems to be on the deprecationrow ... And that as @Juzer Ali pointed out, you might not even need it if you're targeting modern enough browsers.

另外,请注意 _.where 和 _.findWhere 似乎在弃用行......正如@Juzer Ali 指出的那样,如果您的目标是足够现代的浏览器,您甚至可能不需要它。

回答by Juzer Ali

No need to use underscore. These days browsers have these idioms built in. See Array.some.

无需使用下划线。如今,浏览器内置了这些习语。请参阅Array.some

array.some(function(elem){
    return !!elem["name"] === "xxx";
});

From the docs

从文档

some does not mutate the array on which it is called.

some 不会改变调用它的数组。

回答by Praveen Prasannan

Use isEmpty

使用isEmpty

var exists = !_.isEmpty(_.where(array, {name: 'xxx'}));

Fiddle

小提琴