iT邦幫忙

1

【JavaScript】陣列方法之indexOf()

  • 分享至 

  • xImage
  •  

【前言】
本系列為個人前端學習之路的學習筆記,在過往的學習過程中累積了很多筆記,如今想藉著IT邦幫忙這個平台做整理+再複習。
本系列標題一律以【】標示該篇文章主要涉及的內容,例如【JavaScript】、【Vue】等等。
若內容有誤,還麻煩各路大神不吝於點出問題,感激不敬。


在JavaScript中有許多操作陣列的方法,本篇將針對indexOf()

陣列.indexOf()將陣列中的一筆資料作為參數,回傳陣列中該筆資料的索引值。

const array = ["red", "blue", "white"];
console.log(array.indexOf("red")); //得到red的索引值0

得到索引值之後可以做很多事情,最常見的就屬於「找到那筆資料在第幾筆,刪掉它」

const array = ["red", "blue", "white"];
array.splice(array.indexOf("red"),1);
console.log(array); //["blue","white"]

要注意的是,如果將不存在於陣列中的資料作為參數,或是不傳入資料的話,將會回傳-1。

const array = ["red", "blue", "white"];
//不傳入參數
console.log(array.indexOf()); //-1
//查找不存在的資料
console.log(array.indexOf("black"));  //-1

indexOf()的比較方法

indexOf()使用嚴格相等(即===)

const array = [1, 2, 3];
console.log(array.indexOf("1")); //-1,代表找不到符合條件

如果有多筆資料符合條件,indexOf()只會回傳第一筆的索引值

const array = ["red", "blue", "white", "red"];
console.log(array.indexOf("red")); //0,並不會回傳第二個的索引值(3)

當陣列中的資料為物件時,indexOf()是比較參考位置

const a = {
    num: 1
};
const b = {
    num: 1
}
const c = a;
const array = [a, b, c];
console.log(array.indexOf(c)); //0,因為a和c的參考位置相同,即a === c,但如果有多筆資料符合條件,indexOf()只會回傳第一筆的索引值

在這個案例中明明我們想查詢的是c,結果得到的索引值卻是a,正是因為物件傳參考的特性導致的有趣情況
也因為indexOf()是比較物件的參考位置,還會出現這樣的狀況:

const a = {
    num: 1
};
const array = [a];
console.log(array.indexOf({num: 1})); //-1,找不到

明明乍看之下我們要找的東西和a一模一樣,但indexOf()卻回傳-1
這是因為當我們以參數的形式傳入{num: 1}的時候,其本身是一個新物件,有自己的參考位置,而這個參考位置與a是不同的
因此,當indexOf()比較a和{num: 1}的參考位置時,自然會得到false的結果

const a = {
    num: 1
};
console.log(a === {num: 1}); //false

這樣就很明顯知道為什麼會是-1了


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
greenriver
iT邦研究生 5 級 ‧ 2022-03-04 08:29:16

想請問,那如果想把所有的2的index都抓出來,該怎麼抓比較好呢?

假設一個陣列如下

const array=[1,2,3,2,4,5,2,2,8,0,9]

用 reduce 來做

const newArray = array.reduce((acc, curr, idx) => {
  if (curr === 2) {
    acc.push(idx)
  }
  return acc
}, [])
// newArray = [1, 3, 6, 7]
greenriver iT邦研究生 5 級 ‧ 2022-03-04 13:14:50 檢舉

galaxian85
學到一課 感謝
/images/emoticon/emoticon32.gif

galaxian85
我也學到一課,感謝

我要留言

立即登入留言