看看这个代码示例 or go to the jsfiddle
function printRelation(a, b, out) {
var text;
if (a === b) {
text = "a === b";
} else if (a == b) {
text = "a == b";
} else {
text = "a != b";
}
$('#' + out).text(text);
}
var a = [0, 0, 2], b = a;
printRelation(a, b, 'out1');
a = [0, 0, 2];
b = [0, 0, 2];
printRelation(a, b, 'out2');
我希望两个测试都能输出 a === b
,但只有第一个会输出。第二个输出 a != b
。谁能解释这种行为?如何在 javascript 中高效地比较数组?
最佳答案
您可以使用 Underscore.js 库的 isEqual 方法。
http://underscorejs.org/#isEqual
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
var moe = {name : 'moe', luckyNumbers : [13, 27, 34]};
var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
moe == clone;
=> false
_.isEqual(moe, clone);
=> true
更新
Lodash 的灵感来自下划线,但现在是更好的解决方案
https://lodash.com/docs/#isEqual
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
var object = { 'a': 1 };
var other = { 'a': 1 };
_.isEqual(object, other);
// => true
object === other;
// => false
关于javascript - 如何检查数组在 javascript 中是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770373/