Javascript: 明显相等的断言结果不同
Javascript: assertion with aparently equal values resulting different
我有这个 Javascript 代码:
const BaseList = {
new: function(list) {
this.list = list;
return this;
},
sortKeys: function(key) {
const keys = Object.keys(this.list);
keys.push(key);
keys.sort();
return keys;
}
}
module.exports = BaseList;
我正在用 Mocha/Assert 测试 sortKeys
这样做:
describe('#sortKeys', function() {
it('should insert a new key in order', function() {
const par = {'a': 'test_a', 'c': 'test_c'};
const bl = BaseList.new(par);
const sl = bl.sortKeys('b');
assert.equal(sl,['a','b','c']);
});
});
碰巧我的测试失败了,但是失败信息是这样的:
AssertionError [ERR_ASSERTION]: [ 'a', 'b', 'c' ] == [ 'a', 'b', 'c' ]
看起来我们有两个相等的数组,但断言说它们是不同的。
我在这里错过了什么?
在 javascript 中,对象实例(即数组)永远不会相等,即使它们此时包含相同的数据。这是因为 JS 是通过引用来比较对象,而不是通过值。
对于简单的解决方案,只需使用:
assert.equal(sl.toString(),['a','b','c'].toString());
对于 better/more 灵活的解决方案:How to compare arrays in JavaScript?
我有这个 Javascript 代码:
const BaseList = {
new: function(list) {
this.list = list;
return this;
},
sortKeys: function(key) {
const keys = Object.keys(this.list);
keys.push(key);
keys.sort();
return keys;
}
}
module.exports = BaseList;
我正在用 Mocha/Assert 测试 sortKeys
这样做:
describe('#sortKeys', function() {
it('should insert a new key in order', function() {
const par = {'a': 'test_a', 'c': 'test_c'};
const bl = BaseList.new(par);
const sl = bl.sortKeys('b');
assert.equal(sl,['a','b','c']);
});
});
碰巧我的测试失败了,但是失败信息是这样的:
AssertionError [ERR_ASSERTION]: [ 'a', 'b', 'c' ] == [ 'a', 'b', 'c' ]
看起来我们有两个相等的数组,但断言说它们是不同的。
我在这里错过了什么?
在 javascript 中,对象实例(即数组)永远不会相等,即使它们此时包含相同的数据。这是因为 JS 是通过引用来比较对象,而不是通过值。
对于简单的解决方案,只需使用:
assert.equal(sl.toString(),['a','b','c'].toString());
对于 better/more 灵活的解决方案:How to compare arrays in JavaScript?