我的意思是,includes是一个数组原型,但in也可以与数组一起使用,那么两者之间的主要区别是什么?
Ori*_*ori 10
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); // trueRun Code Online (Sandbox Code Playgroud)
Array#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 arrayRun Code Online (Sandbox Code Playgroud)
在数组上使用in是一个相对不常见的操作,主要保留用于稀疏数组。
小智 5
“includes”检查数组中是否存在值,而“in”运算符检查 obj/array 中是否存在键/索引。
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 objRun Code Online (Sandbox Code Playgroud)