Javascript includes() 失败
Javascript includes() failing
为什么最后两个 console.logs 显示错误?
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 中的数组是对象,如果引用的对象不相同,则对象比较总是 return 错误。
如果你想比较数组,你必须为此编写一个函数或使用 lodash 中的 isEqual func
您可以先使用 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);
Array.prototype.includes()
和三等运算符 ===
与 references 一起工作,它们不比较数组的元素,它们比较数组引用本身:
console.log([] === []); // false
const a = [];
const b = a;
console.log(a === b); // true
在 JavaScript 中,数组和对象是通过引用而不是值进行比较的。
我建议的一种解决方案是使用 JSON.stringify()
a = ["a", "b"]
b = ["a", "b"]
console.log(JSON.stringify(a) == JSON.stringify(a)) // return true
为什么最后两个 console.logs 显示错误?
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 中的数组是对象,如果引用的对象不相同,则对象比较总是 return 错误。
如果你想比较数组,你必须为此编写一个函数或使用 lodash 中的 isEqual func
您可以先使用 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);
Array.prototype.includes()
和三等运算符 ===
与 references 一起工作,它们不比较数组的元素,它们比较数组引用本身:
console.log([] === []); // false
const a = [];
const b = a;
console.log(a === b); // true
在 JavaScript 中,数组和对象是通过引用而不是值进行比较的。
我建议的一种解决方案是使用 JSON.stringify()
a = ["a", "b"]
b = ["a", "b"]
console.log(JSON.stringify(a) == JSON.stringify(a)) // return true