“includes”是一个数组原型,而“in”也可以用于数组,那么两者之间的主要区别是什么?
Array.includes()
可用于检查数组中是否存在某个值,而in
运算符可用于检查对象中是否存在某个键(或在数组的情况下,则是索引)。
例如:
var arr = [5];
console.log('Is 5 is an item in the array: ', arr.includes(5)); // true
console.log('do we have the key 5: ', 5 in arr); // false
console.log('we have the key 0: ', 0 in arr); // true
0
存在。但是,由于没有6个项目,索引5不存在。 - Ori DroriArray#includes
方法用于判断给定的值是否为数组中的一个元素。而in
运算符则用于检查给定的字符串是否为对象(或其原型链)上已知的属性。它们是非常不同的东西。
“in”也可以用于数组...
确实可以,用来检查是否存在具有给定名称的属性,但这与includes
的作用完全不同:
var a = [10];
console.log(a.includes(10)); // true, 10 is an entry in
console.log(10 in a); // false, there's no property called "10" in the array
console.log(0 in a); // true, there IS a property called "0" in the array
在数组上使用in
是一种相对不常见的操作,主要用于稀疏数组。
“includes”检查值是否存在于数组中,而“in”运算符则检查键/索引是否存在于对象/数组中。
var arr = [15, 27, 39, 40, 567],
obj = {
num1: 3,
num2: 34,
num3: 89
};;
console.log(arr.includes(27)); // returns true checks 27 as a value in the array
console.log(2 in arr); // returns true checks 2 as index in the array
console.log("num1" in obj); // returns true checks num1 as key in obj
in
运算符可以检查键是否存在,使用includes()
可以检查值是否存在。