const arr = []
for(let i=0; i<1000000; i++) {
arr.push(`ahdgd${i}`)
}
console.time('indexOf')
arr.indexOf('ahdgd10000')
console.timeEnd('indexOf')
// indexOf: 0.0400390625ms
console.time('includes')
arr.includes('ahdgd10000')
console.timeEnd('includes')
// includes: 0.025146484375ms
console.time('hasOwnProperty')
arr.hasOwnProperty('ahdgd10000')
console.timeEnd('hasOwnProperty')
// hasOwnProperty: 0.004150390625ms
通过上面实践可以看出来arr.hasOwnProperty()方法要快的多。
不管是arr.indexOf()还是es6的arr.includes(),本质上都是遍历数组
hasOwnProperty()
方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是是否有指定的键)该方法会忽略掉那些从原型链上继承到的属性。
数组也是对象,数组元素相当于以下标和对应的值存在的建值对。