【问题标题】:Javascript includes() failing [duplicate]Javascript包括()失败[重复]
【发布时间】:2021-05-28 21:02:57
【问题描述】:

为什么最后两个 console.log 显示为 false?

const a = 'one';
const b = 'two';
const myArray = [[ 'one', 'two'], ['three', 'four'], ['five', 'six']];
console.log([a, b]);
console.log(myArray[0]);
console.log(myArray.includes([a, b]));
console.log(myArray[0] === [a, b]);

【问题讨论】:

  • 您应该在问题中将代码作为 sn-p 发布

标签: javascript arrays equality


【解决方案1】:

在 JavaScript 中,数组和对象是通过引用而不是值进行比较的。

我建议的一个解决方案是使用 JSON.stringify()

a = ["a", "b"]
b = ["a", "b"]

console.log(JSON.stringify(a) == JSON.stringify(a)) // return true

【讨论】:

    【解决方案2】:

    Array.prototype.includes() 和三等号运算符 ===references 一起使用,它们不比较数组的元素,而是比较数组引用本身:

    console.log([] === []); // false
    
    const a = [];
    const b = a;
    
    console.log(a === b); // true

    【讨论】:

      【解决方案3】:

      您可以先使用JSON.stringify()将数组(对象)转换为字符串,然后比较字符串:

      const a = 'one';
      const b = 'two';
      const myArray = [
        ['one', 'two'],
        ['three', 'four'],
        ['five', 'six']
      ];
      
      console.log(JSON.stringify(myArray[0]) === JSON.stringify([a, b]));

      您还可以使用 every() 遍历单独的值并像这样比较它们:

      const a = 'one';
      const b = 'two';
      const myArray = [[ 'one', 'two'], ['three', 'four'], ['five', 'six']];
      
      const isequal = [a, b].length === myArray[0].length && [a, b].every((value, i) => value === myArray[0][i]);
      console.log(isequal);

      【讨论】:

      • 如果您知道它在数组中以及它的索引位置,那就太好了。
      • 是的,它们确实必须按正确的顺序排列
      【解决方案4】:

      JavaScript 中的数组是对象,如果引用的对象不同,对象比较总是返回 false。

      如果你想比较数组,你必须为此编写一个函数或使用 lodash 中的 isEqual 函数

      https://lodash.com/docs/4.17.15#isEqual

      【讨论】:

      • "always return false" 仅适用于 NaN,不适用于对象。
      • 对象比较总是返回 false 不,如果引用的对象相同,对象比较将返回 true。
      猜你喜欢
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多