在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

转载于:https://my.oschina.net/xiaohuoni/blog/1547968

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值