使用 _.some 方法测试值是否在带有 underscoreJS 的数组中

Test if value is in array with underscoreJS using _.some method

let array = [1234, 1233, 1232];

console.log(_.some(array, 1234));

它returns false。你知道为什么吗?

根据 documentation of _.some() method,第二个参数应该是谓词函数

console.log(_.some(array, function(v){ return v === 1234}));


在这种特殊情况下,您可以简单地使用本机 javascript Array#indexOf 方法。

console.log(array.indexOf(1234) > -1);


还有原生的JavaScriptArray#some方法

console.log(array.some(function(v){ return v === 1234}));

ES6 arrow function

console.log(array.some(v => v == 1234))

使用 UNDERSCORE.JS 你可以简单地使用,

console.log(_.indexOf(array, 1234) >= 0)

文档以获取更多详细信息: http://underscorejs.org/#indexOf