1
var allCoords = [{ x: 2, y: 3 }, { x: 3, y: 4 }];
var emptySpaces = allCoords;

emptySpaces.splice(0, 1);
console.log(allCoords.length);
console.log(emptySpaces.length);

I do not understand why both of these output "1". Why is the original array, allCoords being modified, when I only want the second one, emptySpaces to be edited?

1 Answers1

-1

Modify your code like this:

(function testing() {
    var allCoords = [];
    var emptySpaces = allCoords.slice();

    emptySpaces.push({
        x: 1,
        y: 2
    });
    console.log(allCoords.length);
    console.log(emptySpaces.length);
}());
Verhaeren
  • 1,661
  • 9
  • 10