indexOf 和 includes的区别

定义和用法

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。

语法

stringObject.indexOf(searchvalue,fromindex)
参数描述
searchvalue必需。规定需检索的字符串值。
fromindex可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。

提示和注释

注释:indexOf() 方法对大小写敏感!

注释:如果要检索的字符串值没有出现,则该方法返回 -1。


语法

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)

参数说明

参数描述
searchElement必须。需要查找的元素值。
fromIndex可选。从该索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。

技术细节

返回值:布尔值。如果找到指定值返回 true,否则返回 false。
JavaScript 版本:ECMAScript 6

使用includes()方法检查NaN

1

2

3

4

5

const  array = [NaN];

 

if (array.includes(NaN)){

   console.log("在数组中找到NaN");

}

这就是用indexOf()方法开始崩溃的地方

1

2

3

4

5

const  array = [NaN];

 

if (array.indexOf(NaN) == -1){

    console.log("在数组中没有NaN");

}

 

判断稀疏数组结果不同

1

2

3

4

5

const array = [, , , ,];

 

if(array.includes(undefined)){

    console.log("在数组中找到undefined");

}

让我们看看indexOf()方法将如何处理这个操作

1

2

3

4

5

const array = [, , , ,];

 

if(array.indexOf(undefined) == -1 ){

    console.log("找不到undefined");

}

 

includes()方法没有区分-0和+0

1

2

const a = [-0].includes(+0);

console.log(a);//true

 

字符串的indexOf和数组中的indexOf的比较
这两个方法都可以接收两个参数
这两个方法在没有查找的指定的字符都返回-1
字符串中的indexOf中的第二个参数支持负数而数组的indexOf不支持
字符串的indexOf在传入参数不是字符串的情况下默认会转换为字符串而数组的indexOf不会进行数据类的转换
字符串的参数不支持负数

let str = "abcd";
let ary = ["a","b","c","d"];
console.log(str.indexOf("a", -1)); //0
console.log(ary.indexOf("a", -1)); //-1

字符串的参数会自动转换

let str = "1";
let ary = ["1"];
console.log(str.indexOf(1)); //0
console.log(ary.indexOf(1)); //-1

字符串的includes和数组中的includes的比较
这两个方法都可以接收两个参数
这两个方法在没有查找的指定的字符都返回false
字符串中的includes中的第二个参数支持负数而数组的includes不支持
字符串的includes在传入参数不是字符串的情况下默认会转换为字符串而数组的includes不会进行数据类的转换
字符串的参数不支持负数

let str = "abcd";
let ary = ["a","b","c","d"];
console.log(str.includes("a", -1)); //true
console.log(ary.includes("a", -1)); //false

字符串的参数会自动转换

let str = "1";
let ary = ["1"];
console.log(str.includes(1)); //true
console.log(ary.includes(1)); //false

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值