Q:

JavaScript pushing to index 1 instead of 0

I have a JavaScript variable, and I'm trying to initialize it in another function, with the following for loop:

var test = {
    det: [{x: -1, y: -1}]
};

for (var i = 0; i < 4; i++) {
        test.det.push({x:10+i, y:10});
}

console.log(test.det);

For some reason, I still get -1 & -1 as my values of x & ywhen I try to access test.det[0]. I only get the first values pushed when I access index 1. It seems like all my indices are shifted but I have no idea why that would be happening.

A:

Array#push will add another item after the current last item. To re initialize use assignment =:

var test = {
  det: [{x: -1, y: -1}]
};

for (var i = 0; i < 4; i++) {
  test.det[i] =  ({x:10+i, y:10});
}

console.log(test);

Or just clear the array, and use Array#push:

var test = {
  det: []
};

for (var i = 0; i < 4; i++) {
  test.det.push({x:10+i, y:10});
}

console.log(test);

