I often give array elements properties so that I don't need to use nested arrays. However, when I copy an array element with array.push(array[0])
or even array[array.length] = array[0]
, they new element and the copied element are becoming linked- when I change a property of one, it changes that property of the other.
Here is the code:
var array = [{num: 0}, {num: 1}, {num: 2}, {num: 3}];
var i;
var nums = "";
array.push(array[0]);
//What the array looks like before anything is changed
for (i = 0; i < array.length; i += 1) {
nums += array[i].num + " ";
}
console.log(nums);
array[0].num = 1;
//What the array looks like after changing only one element
nums = "";
for (i = 0; i < array.length; i += 1) {
nums += array[i].num + " ";
}
console.log(nums);
When this is run, both the first and last elements of array
are changed, despite only running array[0].num = 1
. Does anyone know what's happening and how I can fix it?