findIndex() 是 JavaScript 陣列中很常用的方法之一
它和 find() 很像,但最大的差別是:
find() → 回傳符合條件的元素
findIndex() → 回傳符合條件的索引(index)
findIndex() 會從陣列第一個元素開始尋找。
找到第一個符合條件的元素,就回傳它的索引(index)。
如果整個陣列都找不到,則回傳 -1
array.findIndex(function(item, index, array) {
return 條件;
});
| 參數 | 代表 |
|---|---|
| item | 目前正在檢查的元素 |
| index | 目前元素的位置 |
| array | 原本整個陣列 |
let numbers = [5, 10, 15, 20, 25];
let result = numbers.findIndex(function(item) {
return item === 15;
});
console.log(result); // 輸出 2 索引值
let users = [
{ id: 1, name: "Amy" },
{ id: 2, name: "John" },
{ id: 3, name: "Mary" }
];
let index = users.findIndex(function(user) {
return user.id === 2;
});
console.log(index); //輸出 1 索引值
let users = [
{ id: 1, name: "Amy" },
{ id: 2, name: "John" },
{ id: 3, name: "Mary" }
];
let index = users.findIndex(function(user) {
return user.id === 2;
});
users[index].name = "Peter";
console.log(users);
//輸出
[
{ id: 1, name: "Amy" },
{ id: 2, name: "Peter" },
{ id: 3, name: "Mary" }
]
找到 id=2 → 得到索引 1 → users[1] → 修改資料
| 方法 | 回傳結果 | 找到幾筆 | 找不到 |
|---|---|---|---|
find() |
第一個符合條件的元素 | 1 筆 | undefined |
findIndex() |
第一個符合條件的索引 | 1 筆 | -1 |
filter() |
所有符合條件的元素(新陣列) | 多筆 | [] |
什麼時候使用?
初學者建議:findIndex() 常與「修改」或「刪除」陣列中的資料一起使用,因為知道索引後,可以直接透過 array[index] 操作對應元素。