1.forEach
定义和用法
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
案例
const originalArray = [
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'cherry' }
];
let targetObject;
let targetIndex = -1;
originalArray.forEach((item, index) => {
if (item.id === 2) {
targetObject = item;
targetIndex = index;
break;
}
});
2. findIndex
定义和用法
findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
findIndex() 方法为数组中的每个元素都调用一次函数执行:
- 注意当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 -1
案例
const seIndex = storeList.findIndex((currentValue, index, arr) => currentValue.id === sid);
3. find
定义和用法
find() 方法返回通过测试(函数内判断)的数组的第一个元素的值。
find() 方法为数组中的每个元素都调用一次函数执行:
- 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数
- 如果没有符合条件的元素返回 undefined
注意: find() 对于空数组,函数是不会执行的。
注意: find() 并没有改变数组的原始值。
案例
const arr=[1,2,-3,4,-5];
const negativeNum = arr.find(num => num<0);
console.log(negativeNum);//输出:-3
4. some
some() 方法用于检测数组中的元素是否满足指定条件(函数提供)。
some() 方法会依次执行数组的每个元素:
- 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
- 如果没有满足条件的元素,则返回false。
注意: some() 不会对空数组进行检测。
注意: some() 不会改变原始数组。
案例
const arr=[1,3,5,8,9];
const hasEven =arr.some(num =>
console.log(num);//输出:1,3,5,8(找到8后停止)
return num%2 === 0;
});
console.log(hasEven);//true