Javascript includes() 失败 [duplicate]

Javascript includes() failing [duplicate]

提问人:TribeOfOne 提问时间:2/26/2021 最后编辑:Guerric PTribeOfOne 更新时间:2/26/2021 访问量:479

问:

为什么最后两个console.logs显示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]);

JavaScript 数组 相等

评论

1赞 Guerric P 2/26/2021
您应该将代码作为代码片段发布到您的问题中

答:

1赞 Mikhail Grechka 2/26/2021 #1

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

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

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

评论

0赞 Jonas Wilms 2/26/2021
“always return false”仅对 NaN 为 true,而对对象则不为 true。
0赞 Guerric P 2/26/2021
对象比较将始终返回 false否,如果引用的对象相同,则对象比较将返回 true。
2赞 axtck 2/26/2021 #2

您可以先使用 将数组(对象)转换为字符串,然后比较字符串: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);

评论

1赞 phuzi 2/26/2021
如果您知道它在数组中以及它位于哪个索引处,那就太好了。
0赞 axtck 2/26/2021
是的,确实,它们必须按正确的顺序排列
2赞 Guerric P 2/26/2021 #3

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

console.log([] === []); // false

const a = [];
const b = a;

console.log(a === b); // true

2赞 maziyank 2/26/2021 #4

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

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

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

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