JavaScript Array findIndex() (尋找陣列元素索引)

陣列 (array) 的 findIndex() 方法用來找出陣列中第一個符合條件的元素的索引位置。如果找到就回傳該元素的索引值;如果沒有找到,回傳 -1

語法:

const index = arr.findIndex(callback[, thisArg])
  • 參數 callback 是一個測試函數,會接收到三個參數:
    • currentValue 代表目前處理到的元素的值
    • index 代表目前處理到的元素的索引位置
    • array 代表陣列本身
    • 根據 callback 的執行結果,返回 true 表示找到了;返回 false 則繼續找下一個
  • thisArg 代表 callback 裡面的 this 是指向哪一個物件
  • findIndex() 執行結果會返回第一個符合條件的元素索引,或 -1

用法:

const numbers = [5, 12, 8, 130, 44];

const index = numbers.findIndex(function (element) {
  return element > 10;
});

console.log(index); // 1(12 的索引位置)

尋找物件陣列中的元素索引:

const users = [
  { id: 1, name: 'Mike' },
  { id: 2, name: 'Alice' },
  { id: 3, name: 'John' },
];

const index = users.findIndex(function (user) {
  return user.id === 2;
});
// 1
console.log(index);

// 使用 Arrow Function
const index2 = users.findIndex((user) => user.id === 2);
// 1
console.log(index2);

和 indexOf() 的差異:

const numbers = [5, 12, 8, 130, 44];

// indexOf 只能找特定的值
numbers.indexOf(12); // 1

// findIndex 可以用條件函數,更有彈性
numbers.findIndex((n) => n > 10); // 1
findIndex() 是 ES6 新增的方法。如果只需要用特定值來找索引,可以用 indexOf();如果需要找元素本身,可以用 find()