0

I'm trying the following code:

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']);
    });
});

This expectation fails, but why? shouldn't it equal?

Andy
  • 17,423
  • 9
  • 52
  • 69

1 Answers1

0

There is a difference in JavaScript between array that has 3 elements one of them is undefined and array that has only 2 elements. For example

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

also

1 in a
// returns false

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

Source is always on your side, if you look at toEquals matcher code you will find that it uses eq function from following source file (it is a bit lengthy so I provide only link, at the bottom is the part that compares objects and arrays: https://github.com/jasmine/jasmine/blob/79206ccff5dd8a8b2970ccf5a6429cdab2c6010a/src/core/matchers/matchersUtil.js).

csharpfolk
  • 4,124
  • 25
  • 31