首先includes是es6中方法,indexOf是es5中的方法
indexOf和includes都代表检测数组或字符串中是否包含某一个元素
其中indexOf返回的是数值类型,而includes返回的是布尔类型
如果想查找某个元素在数组中的索引位置,就用indexOf
如果想查找某个元素在数组中是否存在,就用includes
var ary = [1,2];
if (ary.indexOf(1) !== -1) {
console.log("数组存在1")
}
if (ary.includes(1)) {
console.log("数组存在1")
}
如果数组中有NaN,你又正好需要判断数组是否有存在NaN,这时你使用indexOf是无法判断的,你必须使用includes这个方法。
var ary1 = [NaN];
console.log(ary1.indexOf(NaN))//-1
console.log(ary1.includes(NaN))//true
当数组的有空的值的时候,includes会认为空的值是undefined,而indexOf不会。
var ary = [,,]; console.log(ary.indexOf(undefined))//-1 console.log(ary.includes(undefined))//true
var ary1 = new Array(3);
console.log(ary1.indexOf(undefined));//-1
console.log(ary1.includes(undefined))//true
总结:
两者都是字符串和数组共同的方法
字符串的indexOf和数组中的indexOf的比较
1 这两个方法都可以接收两个参数 2 这两个方法在没有查找的指定的字符都返回-1 3 字符串中的indexOf中的第二个参数不支持负数而数组的indexOf支持 4 字符串的indexOf在传入参数不是字符串的情况下默认会转换为字符串而数组的indexOf不会进行数据类的转换
字符串的includes和数组中的includes的比较
1 这两个方法都可以接收两个参数 2 这两个方法在没有查找的指定的字符都返回false 3 字符串中的includes中的第二个参数不支持负数而数组的includes支持 4 字符串的includes在传入参数不是字符串的情况下默认会转换为字符串而数组的includes不会进行数据类的转换