0

我正在尝试以下代码:

describe("array deletion", function () {
    it("leaves a hole in middle", function () {
        var array = ['one','two','three'];
        delete array[1]; //'two' deleted
        expect(array).toEqual(['one',undefined,'three']);
    });
});

这种期望失败了,但为什么呢?不应该相等吗?

4

1 回答 1

0

JavaScript 中有 3 个元素其中之一的undefined数组和只有 2 个元素的数组之间存在差异。例如

var a = [1,2,3];
delete a[1];
a.forEach(function(x) { console.log(x); });
// writes 1 3

[1,undefined,3].forEach(function(x) { console.log(x); })
// writes 1 undefined 3

1 in a
// returns false

1 in [1,undefined,2]
// returns true

源始终在您身边,如果您查看toEquals匹配器代码,您会发现它使用eq以下源文件中的函数(它有点长,所以我只提供链接,底部是比较对象和数组的部分:https: //github.com/jasmine/jasmine/blob/79206ccff5dd8a8b2970ccf5a6429cdab2c6010a/src/core/matchers/matchersUtil.js)。

于 2016-01-15T16:51:40.020 回答