Array.prototype.includes()方法
includes()
的作用,是查找一个值在不在数组里,若在,则返回true
,反之返回false
。 基本用法:
['a', 'b', 'c'].includes('a') // true
['a', 'b', 'c'].includes('d') // false
Array.prototype.includes()方法接收两个参数:要搜索的值和搜索的开始索引。当第二个参数被传入时,该方法会从索引处开始往后搜索(默认索引值为0)。若搜索值在数组中存在则返回true
,否则返回false
。 且看下面示例:
['a', 'b', 'c', 'd'].includes('b') // true
['a', 'b', 'c', 'd'].includes('b', 1) // true
['a', 'b', 'c', 'd'].includes('b', 2) // false
那么,我们会联想到ES6里数组的另一个方法indexOf,下面的示例代码是等效的:
['a', 'b', 'c'].includes('a') //true
['a', 'b', 'c'].indexOf('a') > -1 //true
两者使用的都是 === 操作符来做值的比较。但是includes()方法有一点不同,两个NaN被认为是相等的,即使在NaN === NaN
结果是false
的情况下。这一点和indexOf()
的行为不同,indexOf()
严格使用===
判断。请看下面示例代码:
let demo = [1, NaN, 2, 3]
demo.indexOf(NaN) //-1
demo.includes(NaN) //true
includes()
还有一个怪异的点需要指出,在判断 +0 与 -0 时,被认为是相同的。
[1, +0, 3, 4].includes(-0) //true
[1, +0, 3, 4].indexOf(-0) //1
在这一点上,indexOf()
与includes()
的处理结果是一样的,前者同样会返回 +0 的索引值。