includes介绍及用法
1.介绍
includes方法用来判断一个数组是否包含一个指定值的,如果包含则返回true,否则返回false。
2.用法
includes(searchElement)
includes(searchElement, fromIndex)
参数介绍:searchElement:需要查找的值。
formIndex:开始搜索的索引(从0开始)
2.1基础用法
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// Expected output: true
const arr=2;
console.log([1,2,3,4].includes(arr));
//true
注意:formIndex大于等于数组的长度,返回false,并且不搜索数组。如果计算出的索引小于0时(计算规则:arr,length+formIndex)返回true,否则返回false。
2.2非数组对象使用
const arrayLike = {
length: 3,
0: 2,
1: 3,
2: 4,
};
console.log(Array.prototype.includes.call(arrayLike, 2));
// true
console.log(Array.prototype.includes.call(arrayLike, 1));
// false
some介绍及用法
1.介绍
测试数组中是否至少有一个元素通过了由提供的函数实现的测试。如果在数组中找到一个元素使得提供的函数返回 true,则返回 true;否则返回 false。它不会修改数组。
2.用法
some(callbackFn)
some(callbackFn, thisArg)
参数介绍:callback:为数组中的每个元素执行的函数。它应该返回一个真值以指示元素通过测试,否则返回一个假值。该函数被调用时将传入以下参数:element:数组中当前正在处理的元素。index:正在处理的元素在数组中的索引。arr:调用了 some()的数组本身。
thisArg:执行 callbackFn
时用作 this
的值。
const array = [1, 2, 3, 4, 5];
// Checks whether an element is even
const even = (element) => element % 2 === 0;
console.log(array.some(even));
// Expected output: true
every介绍及用法
1.介绍
测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。
2.用法
用法与some基本相同,参考some的用法。
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// Expected output: true
总结
这三种方法都能测试数组是否包含元素,并且返回布尔值,在实际项目开发中可以使用来减少判断。