JavaScript 五四三 Ep.07 Array.prototype.indexOf()


Posted by ABow_Chen on 2022-10-07

一、indexOf() 簡介

  1. 對陣列使用 indexOf() 方法,會找到給定的(要搜尋的)元素,在陣列裡第一個被找到的索引值,如果給定元素不存在於陣列中,則會回傳 -1。

二、indexOf() 語法

arr.indexOf(searchElement[, fromIndex])

searchElement: 要搜尋的元素。

fromIndex(選擇性):

  • 要從此陣列開始搜尋 searchElement 的索引位置,預設為 0。
  • 若 fromIndex 大於或等於陣列長度,則直接回傳 -1。
  • 如果為負數,則會從陣列最後一個數值往回算(從右至左),陣列中最後一個值為之索引為 -1。
  • 承上,如果往回算至陣列結束,fromIndex + array.length 仍小於 0,則會由左至右全部搜尋。

    e.g. fromIndex 為 -5,陣列長度為 3,最後一個數值的索引值為 -1,往回算起陣列之起始索引位置 0,由右至左分別為 -1、-2、-3,無法算至 -5,fromIndex + array.length = -2 仍小於 0,所以在此情境下,會由左至右搜尋整個陣列)

語法的執行範例如下:

const pets = ['dog', 'cat', 'rabbit'];

console.log(pets.indexOf('cat')); // 1
console.log(pets.indexOf('rabbit', 2)); // 2
console.log(pets.indexOf('bird')); // -1

三、indexOf() 常見用法、情境

  1. fromIndex 大於或等於陣列長度

     const pets = ['dog', 'cat', 'rabbit'];
    
     //等於陣列長度
     console.log(pets.indexOf('cat', 2)); // -1
    
     // 大於陣列長度
     console.log(pets.indexOf('cat', 3)); // -1
    
  2. fromIndex 為負數

     const pets = ['dog', 'cat', 'rabbit'];
    
     // 索引值為負數,會由最後一個值 'rabbit'(-1) 開始往回算,因此會從 -2 的 'cat' 當成起始值,
     // 開始搜尋
     console.log(pets.indexOf('rabbit', -2)); // 2
    
     // 索引值為負數,往回算後,仍無法算至 -5,arr.length + fromIndex = -2 仍小於 0,
     // 因此會再從左到右搜尋整個陣列
     console.log(pets.indexOf('cat', -5)); // 2
    

參考資料:

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

https://ithelp.ithome.com.tw/articles/10227363


#javascript #indexOf







Related Posts

Unlocking the Secrets: How to Farm Diablo 4 Gold and Rare Items Like a Pro

Unlocking the Secrets: How to Farm Diablo 4 Gold and Rare Items Like a Pro

FB 我的這一天 Nas 版

FB 我的這一天 Nas 版

Jest - mock read-only data

Jest - mock read-only data


Comments