找出JavaScript数组是否包含值的最简洁有效的方法是什么?
这是我知道的唯一方法:
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
有没有更好、更简洁的方法来实现这一点?
这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。
使用indexOf()
可以使用indexOf()方法检查数组中是否存在给定的值或元素。如果找到数组中元素的索引,indexOf()方法返回该元素的索引;如果找不到,则返回-1。让我们看一下以下示例:
var fruits=[“苹果”、“香蕉”、“芒果”、“橙子”、“木瓜”];var a=“芒果”;checkArray(a,水果);函数checkArray(a,fruits){//检查fruits数组中是否存在值如果(fruits.indexOf(a)!==-1) {return document.write(“true”);}其他{return document.write(“false”);}}
使用include()方法
ES6引入了includes()方法来非常容易地执行此任务。但是,此方法只返回true或false,而不返回索引号:
var fruits=[“苹果”、“香蕉”、“芒果”、“橙子”、“木瓜”];警报(水果,包括(“香蕉”));//输出:真警报(水果,包括(“椰子”));//输出:假警报(水果,包括(“橙色”));//输出:真警报(水果,包括(“樱桃”));//输出:假
如需进一步参考,请在此处结账
ECMAScript 7引入了Array.prototype.includes。
它可以这样使用:
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
它还接受来自Index的可选第二个参数:
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
与使用严格相等比较的indexOf不同,indexOf包括使用SameValueZero相等算法的比较。这意味着您可以检测阵列是否包含NaN:
[1, 2, NaN].includes(NaN); // true
与indexOf不同,includes不会跳过缺少的索引:
new Array(5).includes(undefined); // true
它可以是多填充的,以使其在所有浏览器上都可以使用。
这可能是一个详细而简单的解决方案。
//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
}
除了其他人所说的之外,如果没有要在数组中搜索的对象的引用,那么可以执行类似的操作。
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。