How come with this
var prodataTemp = [];
prodataTemp = prodata;
prodataTemp.shift();
both variable prodatTemp and prodata are shifted? I can see it in the console.
How come with this
var prodataTemp = [];
prodataTemp = prodata;
prodataTemp.shift();
both variable prodatTemp and prodata are shifted? I can see it in the console.
Assigning a JavaScript object to another variable, will not copy the contents, but it make the left hand side variable, a reference to the right hand side expression. So,
var prodataTemp = [];
made prodataTemp
refer an empty array and then
prodataTemp = prodata;
makes prodataTemp
refer the same array object prodata
was pointing to. (So, the old empty array is no more referenced by prodataTemp
).
To actually make a copy**, use Array.prototype.slice
, like this
prodataTemp = prodata.slice();
Now, prodataTemp
refers to the copy of the array prodata
, so that shifting one will not affect the other.
** - The copy made is just a shallow copy. So, if you have an array of arrays, then a new array will be created with all the references to the elements of the old array. So, mutating one array element will have its impact in the other as well.