紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS Array.indexOf() 用法:查找元素位置

JS Array.indexOf() 用法:查找元素位置 特色圖片

Array.prototype.indexOf()(通常簡稱 Array.indexOf())是 JavaScript 用來查找元素位置的內建方法:你給它一個要找的值,它回傳這個值在陣列中第一次出現的索引;找不到就回傳 -1。

白話一點,就像在一排座位中找人:回報的是「第幾個座位」(從 0 開始算),找不到人就回報 -1。

語法與回傳值

arr.indexOf(searchElement)
arr.indexOf(searchElement, fromIndex)
項目說明
searchElement要在陣列中尋找的值
fromIndex選填,從哪個索引開始往後找(從 0 起算);省略時從 0 開始,搜尋整個陣列
回傳值searchElement 第一次出現的索引;找不到回傳 -1

以上依 MDN 的 Array.prototype.indexOf() 頁面整理。

基本用法

const fruits = ['apple', 'banana', 'mango', 'banana'];

console.log(fruits.indexOf('banana')); // 1(只回傳第一個)
console.log(fruits.indexOf('grape'));  // -1(找不到)
console.log(fruits.indexOf('Banana')); // -1(大小寫不同視為不同字串)

即使 'banana' 出現了兩次,indexOf() 只回傳最前面的位置。

用 fromIndex 指定起點

第二個參數 fromIndex 可以指定從哪個位置開始找:

const fruits = ['apple', 'banana', 'mango', 'banana'];

console.log(fruits.indexOf('banana', 2)); // 3(從索引 2 開始往後找)

fromIndex 為負數時,表示從陣列尾端往前算起點,但搜尋方向仍然是由前往後:

const array = [2, 9, 9];

console.log(array.indexOf(9, -2)); // 1(-2 換算成起點索引 1)
console.log(array.indexOf(2, -1)); // -1(起點在索引 2,後面沒有 2)
console.log(array.indexOf(2, -3)); // 0

規則依 MDN 整理如下:

fromIndex 的值實際行為
省略,或小於 -array.length從 0 開始,搜尋整個陣列
介於 -array.length 與 -1以 fromIndex + array.length 為起點
大於或等於 array.length不搜尋,直接回傳 -1

判斷元素是否存在

因為找不到時回傳 -1,判斷「有沒有這個元素」要和 -1 比較:

const fruits = ['apple', 'banana', 'mango', 'banana'];
const idx = fruits.indexOf('mango');

if (idx !== -1) {
  console.log('找到了,位置', idx); // 找到了,位置 2
}

不能直接把回傳值當布林用:第一個元素的索引是 0(假值),找不到的 -1 反而是真值:

console.log(fruits.indexOf('apple') ? 'truthy' : 'falsy(0)');  // falsy(0)
console.log(fruits.indexOf('grape') ? 'truthy(-1)' : 'falsy'); // truthy(-1)

如果只想知道「有沒有」,不需要位置,可以改用 includes(),直接回傳 true 或 false。

找出所有出現的位置

indexOf() 一次只回傳一個位置。要找出全部,可以用 fromIndex 接著上一次的位置往後找,直到回傳 -1:

const indices = [];
const letters = ['a', 'b', 'a', 'c', 'a', 'd'];
let i = letters.indexOf('a');

while (i !== -1) {
  indices.push(i);
  i = letters.indexOf('a', i + 1);
}

console.log(indices); // [ 0, 2, 4 ]

不存在才新增

常見的用法是先檢查陣列有沒有這個值,沒有才加進去:

const veggies = ['potato', 'tomato'];

function addIfMissing(list, item) {
  if (list.indexOf(item) === -1) {
    list.push(item);
    console.log('新增後:' + list); // 新增後:potato,tomato,spinach
  } else {
    console.log(item + ' 已存在');
  }
}

addIfMissing(veggies, 'spinach');
addIfMissing(veggies, 'spinach'); // spinach 已存在

注意事項

  1. 用嚴格相等(===)比較:MDN 說明 indexOf() 與 === 使用同一套比較演算法,所以不會做型別轉換:
    console.log([1, 2, 3].indexOf('2')); // -1(字串 '2' 不等於數字 2)
    console.log([1, 2, 3].indexOf(2));   // 1
  2. 找不到 NaN:NaN === NaN 為 false,所以 indexOf(NaN) 一律回傳 -1。要找 NaN 可以改用 includes():
    console.log([NaN].indexOf(NaN));  // -1
    console.log([NaN].includes(NaN)); // true
  3. 物件要比對「同一個參照」:陣列裡的物件用 === 比較的是參照(reference),內容相同但不是同一個物件會找不到。要用條件找物件,改用 findIndex():
    const users = [{ id: 1 }, { id: 2 }];
    
    console.log(users.indexOf({ id: 1 }));                // -1(新建立的物件)
    console.log(users.indexOf(users[1]));                 // 1(同一個參照)
    console.log(users.findIndex((u) => u.id === 2));      // 1(用條件找)
  4. 會跳過稀疏陣列的空位:MDN 說明 indexOf() 會略過空位(empty slot),所以也找不到空位:
    console.log([1, , 3].indexOf(undefined)); // -1
  5. 不限於陣列:MDN 說明 indexOf() 是通用(generic)方法,只要求 this 有 length 屬性與整數鍵的屬性,因此可以對類陣列物件使用:
    const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, 3: 5 };
    
    console.log(Array.prototype.indexOf.call(arrayLike, 2)); // 0
    console.log(Array.prototype.indexOf.call(arrayLike, 5)); // -1(索引 3 超出 length,被忽略)

補充說明:字串也有同名的 String.prototype.indexOf(),用途是找子字串的位置,和陣列的 indexOf() 是兩個不同的方法,例如 'abc'.indexOf('b') 回傳 1。

參考資料與延伸閱讀

發佈留言