JavaScript判断数组是否包含某个值
目录:
- 1.for循环/while循环
- 2.数组的some方法
- 3.数组的filter方法
- 4.array.indexOf
- 5.array.findIndex
- 6.array.includes
- 7.array.find
- 8.set中的has方法
1.for循环/while循环
for循环:
function contains(arr, val) {for (var i = 0; i < arr.length; i++) {if (arr[i] === val) {return true;}}return false;
}
contains([1,2,3],3);//true
while循环:
function contains(arr, val) {var i = arr.length;while (i--) {if (arr[i] === val){return true;}}return false;
}
2.数组的some方法
使用some方法更简洁,一旦找到元素,迭代就会中止,从而避免了不必要的迭代周期。
function contains(arr, val) {return arr.some(item => item === val);
}
3.数组的filter方法
使用filter方法(注意:array.filter(e=>e==x).length > 0等效于array.some(e=>e==x)
但some更有效)
function contains(arr, val) {return arr.filter((item)=> { return item == val }).length > 0;
}
4.array.indexOf
array.indexOf此方法判断数组中是否存在某个值,如果存在返回数组元素的下标,否则返回-1。
[1, 2, 3].indexOf(1);//0
["foo", "fly63", "baz"].indexOf("fly63");//1
[1, 2, 3].indexOf(4);//-1
注意点:
1、indexOf() 方法对大小写敏感!如果要检索的字符串值没有出现,则该方法返回 -1。
2、在比较第一个参数与数组中的每一项时,会使用全等操作符,即要求查找的项必须严格相等
3、数组的位置是ECMAScript5为数组实例新增的,支持的浏览器有IE9+,Firefox,Safari,Opera,Chrome
5.array.findIndex
array.findIndex返回数组中满足条件的第一个元素的索引(下标), 如果没有找到,返回-1:
let dataArray = [{ id: 1, name: '张三', age: 18, nickname: 'Lily' },{ id: 2, name: '李四', age: 22, nickname: null },{ id: 3, name: '王五', age: 25, nickname: 'Mike' }
];console.log(dataArray[dataArray.findIndex((item) => item.id == 3)]);
// {id: 3, name: '王五', age: 25, nickname: 'Mike' }
// 注意:普通函数写法记得加 return
console.log(dataArray[dataArray.findIndex(function(item) { return item.id == 2; })]);
// {id: 2, name: '李四', age: 22, nickname: null }
indexOf和findIndex的差别:
1、indexOf:查找值作为第一个参数,采用绝对相等(===)比较,更多的是用于查找基本类型的数据,如果是对象类型,则是判断是否是同一个对象的引用。
2、findIndex:比较函数作为第一个参数,多用于非基本类型(例如对象)的数组索引查找,或查找条件很复杂。
总结:findIndex比indexOf更强大一些,可以通过回调函数查找对象数组,indexOf只能查找数组中指定的值,不过indexOf可以指定开始查找位置的索引。
6.array.includes
array.includes(searchElement[, fromIndex]) 此方法判断数组中是否存在某个值,如果存在返回 true,否则返回false。
// 一般用法
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false// 它还接受可选的第二个参数fromIndex:
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true// 不像indexOf,它采用严格相等比较。这意味着可以检测数组是否包含NaN:
[1, 2, NaN].includes(NaN); // true// 也不同于indexOf,includes不会跳过缺失的索引:
new Array(5).includes(undefined); // true
7.array.find
find用于返回数组中满足条件的第一个元素的值,如果没有,返回undefined:
let numbers = [12, 5, 8, 130, 44];
let result = numbers.find(item => {return item > 8;
});
console.log(result);//12
//元素是对象
let items = [{id: 1, name: 'something'},{id: 2, name: 'anything'},{id: 3, name: 'nothing'},
];
let item = items.find(item => {return item.id == 3;
});
console.log(item) //Object { id: 3, name: "nothing" }
8.set中的has方法
通过new set([])将数组转换成Set对象,set.prototype.has(value)判断该值是否存在于Set对象中,返回布尔值:
function contains(arr, val) {return new Set(arr).has(val)
}
contains([1,2,3],2);//true
延伸:除此之外,还可以利用它进行数组去重,比如:
let arr2 = new Set([1,1,2,3,4])
let arr3 = [...arr2]
console.log(arr2, arr3) // {1,2,3,4} [1,2,3,4]