JavaScript数组中,“in运算符”和“includes()”有什么区别?

17
“includes”是一个数组原型,而“in”也可以用于数组,那么两者之间的主要区别是什么?

它们的区别在于它们执行不同的任务。 - user202729
答案可以通过一点研究找到。您可以使用以下链接学习它们... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in 和 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes - Waleed Iqbal
"includes" 也是一个字符串方法。 - Andy
4个回答

26

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


为什么第二个console.log行返回false而第三个不返回? - Ray
2
由于数组中只有一个项目,属性0存在。但是,由于没有6个项目,索引5不存在。 - Ori Drori
哦,那样就有意义了,谢谢! - Ray

5

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 array

在数组上使用in是一种相对不常见的操作,主要用于稀疏数组


5

“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


3
使用in运算符可以检查键是否存在,使用includes()可以检查值是否存在。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接