1.forEach
定義和用法
forEach() 方法用于調(diào)用數(shù)組的每個(gè)元素汪厨,并將元素傳遞給回調(diào)函數(shù)秀撇。
注意: forEach() 對(duì)于空數(shù)組是不會(huì)執(zhí)行回調(diào)函數(shù)的斟赚。
案例
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() 方法返回傳入一個(gè)測(cè)試條件(函數(shù))符合條件的數(shù)組第一個(gè)元素位置废菱。
findIndex() 方法為數(shù)組中的每個(gè)元素都調(diào)用一次函數(shù)執(zhí)行:
- 注意當(dāng)數(shù)組中的元素在測(cè)試條件時(shí)返回 true 時(shí), findIndex() 返回符合條件的元素的索引位置,之后的值不會(huì)再調(diào)用執(zhí)行函數(shù)化漆。
- 如果沒有符合條件的元素返回 -1
案例
const seIndex = storeList.findIndex((currentValue, index, arr) => currentValue.id === sid);