【问题标题】:What is the difference between "in operator" and "includes()" for JavaScript arraysJavaScript 数组的“in 运算符”和“includes()”有什么区别
【发布时间】:2021-11-20 21:34:46
【问题描述】:

我的意思是,includes 是一个数组原型,但in 也可以与数组一起使用,那么两者之间的主要区别是什么?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

Array.includes() 检查数组中是否存在值,而in operator 检查对象中是否存在键(或数组中的索引)。

例子:

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而第三行没有?
  • 由于数组中只有一个元素,所以属性0是存在的。但是,由于没有 6 个项目,因此索引 5 不存在。
  • 哦,有道理,谢谢!
【解决方案2】:

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 是一个相对不寻常的操作,主要保留用于sparse arrays

【讨论】:

    【解决方案3】:

    in 操作符可以检查键是否存在,includes() 可以检查值是否存在

    【讨论】:

      【解决方案4】:

      “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 obj

      【讨论】:

        猜你喜欢
        • 2011-08-20
        • 2010-12-25
        • 1970-01-01
        • 2017-04-21
        • 1970-01-01
        • 2022-06-10
        • 2018-08-16
        相关资源
        最近更新 更多