2026年5月11日 星期一

再探 Array.indexof()

 再探 Array.indexof()

前言

  在先前的 關於 Array.indexof() 介紹基本用法,發現未介紹它其實可以像 關於 String.indexOf() 指定從某個位址開始找,並不一定要找第一個,在此把學習的過程做個紀錄。


內容

  範例如下

const array = [2, 9, 3, 4, 9, 8 ];
console.log( array.indexOf( 9 ) );//1
console.log( array.indexOf( 9 , 2 ) );//4
console.log( array.indexOf( 9 , 99 ) );//-1


用法和  關於 String.indexOf() 一樣,只要透過第二個引數來指定開始找的索引,範例開始依舊方法找第一個,第二例就指定從 2 開始找,所以找到的是第二個 9 的索引,這個指定所以是可以大於陣列的大小的,只是結果一定是 -1 (找不到) 。

 

參考資料

[ developer.mozilla.org ] Array.prototype.indexOf()


相關文章與資料

關於 String.indexOf()

關於 Array.includes()

關於 Array.indexof()

沒有留言:

張貼留言