0

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.

1 Answer 1

3
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) 
Sign up to request clarification or add additional context in comments.

2 Comments

var d = c.splice(0); d.splice(0, 3); console.log(c); // prints blank console.log(d); // prints 1 object
@Luckyy - Sorry, my mistake. The method names are very similar, it's actually slice (no p) - see my update above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.