Reputation: 1031
Hi I have this simple script in my code,
var c = [{a: 'apple'},{b: 'ball'},{c: 'ball'},{d: 'ball'}];
console.log(c); //prints 3 objects
var d = c;
d.splice(0, 3);
console.log(c); //prints 1 object
console.log(d); //prints 1 object
What is strange to me is both c and d after splice results same thing (after deleting 3 objects from c whereas I have deleted from d only not c).
Using d.splice(0, 3)
it should delete from 'd' why would it delete from 'c' too ??? any ideas ?? where am I missing something, pls guide me.
Upvotes: 0
Views: 231
Reputation: 16959
var d = c;
This is referencing the array, not duplicating it.
To duplicate it and make d
a completely separate array, use .slice(0)
var d = c.slice(0)
Upvotes: 3