找出JavaScript数组是否包含值的最简洁有效的方法是什么?
这是我知道的唯一方法:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
有没有更好、更简洁的方法来实现这一点?
这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。
这可能是一个详细而简单的解决方案。
//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
// value exists in array
//write some codes
}
// array with objects
var arr = [
{x:'a', y:'b'},
{x:'p', y:'q'}
];
// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p')
{
return elm; // returns length = 1 (object exists in array)
}
});
// or y:'q' exists in arr
var check = arr.filter(function (elm){
if (elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
if (elm.x == 'p' && elm.y == 'q')
{
return elm; // returns length = 1 (object exists in array)
}
});
// in all cases
console.log(check.length); // returns 1
if (check.length > 0)
{
// returns true
// object exists in array
//write some codes
}
假设您定义了这样一个数组:
const array = [1, 2, 3, 4]
下面是三种检查其中是否有3的方法。所有这些都返回true或false。
本机阵列方法(自ES2016以来)(兼容性表)
array.includes(3) // true
作为自定义数组方法(ES2016之前)
// Prefixing the method with '_' to avoid name clashes
Object.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})
array._includes(3) // true
简单的功能
const includes = (a, v) => a.indexOf(v) !== -1
includes(array, 3) // true
除了其他人所说的之外,如果没有要在数组中搜索的对象的引用,那么可以执行类似的操作。
let array = [1, 2, 3, 4, {"key": "value"}];
array.some((element) => JSON.stringify(element) === JSON.stringify({"key": "value"})) // true
array.some((element) => JSON.stringify(element) === JSON.stringify({})) // true
如果任何元素与给定条件匹配,Array.some返回true;如果没有元素与给定的条件匹配,则返回false。
上面的答案假设是基元类型,但如果您想知道数组是否包含具有某种特征的对象,array.protocol.some()是一个很好的解决方案:
const items = [ {a: '1'}, {a: '2'}, {a: '3'} ]
items.some(item => item.a === '3') // returns true
items.some(item => item.a === '4') // returns false
它的好处是,一旦找到元素,迭代就被中止,从而避免了不必要的迭代周期。
此外,它很适合if语句,因为它返回布尔值:
if (items.some(item => item.a === '3')) {
// do something
}
*正如jamess在评论中指出的那样,在2018年9月回答这个问题时,Array.protocol.some()是完全支持的:caniuse.com支持表