在JavaScript中includes()和indexOf()的比較

ES2016 規格包括數組數據結構的 includes() 方法。
Includes() 方法檢查是否數組包含某些元素,返回 true 或 false 。
但在 ES5 我們習慣於執行操作 indexOf () 方法。


使用 includes()方法。

const array = [1,2,3,4,5,6];

if(array.includes(4) ){
   console.log("在數組中找到4");
} 

使用indexOf()方法執行相同的操作。

const array = [1,2,3,4,5,6];

if(array.indexOf(4) > -1 ){
   console.log("在數組中找到4");
}   

使用includes()方法檢查NaN

const  array = [NaN];

if (array.includes(NaN)){
   console.log("在數組中找到NaN");
}

這就是用indexOf()方法開始崩潰的地方

const  array = [NaN];

if (array.indexOf(NaN) == -1){
    console.log("在數組中沒有NaN");
}

使用includes() 方法檢查undefined

const array = [, , , ,];

if(array.includes(undefined)){
    console.log("在數組中找到undefined");
} 

讓我們看看indexOf()方法將如何處理這個操作。

const array = [, , , ,];

if(array.indexOf(undefined) == -1 ){
    console.log("找不到undefined");
}

下面我們來看幾個includes()的表現

includes()方法沒有區分-0和+0

const a = [-0].includes(+0);
console.log(a);//true

系列化數組(Typed Arrays)也包含includes()方法

let array = Uint8Array.of(2,6,4);
console.log(array.includes(4));//true

原文作者:John Samuel Obinna
原文鏈接:https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

發佈了75 篇原創文章 · 獲贊 61 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章