在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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章