JS---数组方法知识补充

93 阅读1分钟

indexOf()和includes()方法比较

此两种方法都可以用于判断一个元素是否存在于数组中,但个人觉得includes用起来更方便严谨些

区别:

1、返回值

indexOf找到返回索引下标值,找不到返回 -1

includes返回的是布尔值,找到返回 true,找不到返回 false

const names = ["we", "sd", "xc", "gh"];

const backValue1 = names.indexOf('sd')
const backValue2 = names.indexOf('sdsd')

console.log(backValue1, backValue2);//1  -1


const backValue3 = names.includes('sd')
const backValue4 = names.includes('sdsd')

console.log(backValue3, backValue4);//true false

2、对NaN的判断

includes方法可以判断出数组中是否存在NaN值,而indexOf无法正确判断出来

const names = ["we", "sd", "xc", "gh", NaN];

const backValue1 = names.indexOf(NaN)
const backValue2 = names.includes(NaN)

console.log(backValue1, backValue2);//-1  true