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

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

語法:

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

用法:

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

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

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

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

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

var index = users.findIndex(function(user) {
    return user.id === 2;
});

console.log(index);  // 1

使用箭頭函數 (ES6):

var index = numbers.findIndex(element => element > 10);

和 indexOf() 的差異:

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

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

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