Skip to content Skip to sidebar Skip to footer

Using Splice(0) To Duplicate Arrays

I have two arrays: ArrayA and ArrayB. I need to copy ArrayA into ArrayB (as opposed to create a reference) and I've been using .splice(0) but I noticed that it seems to removes the

Solution 1:

You want to use slice() (MDN docu) and not splice() (MDN docu)!

ArrayB = ArrayA.slice(0);

slice() leaves the original array untouched and just creates a copy.

splice() on the other hand just modifies the original array by inserting or deleting elements.

Solution 2:

splice(0) grabs all the items from 0 onwards (i.e. until the last one, i.e. all of them), removes them from the original array and returns them.

Solution 3:

You are looking for slice:

var a = [1,2,3,4,5]
   ,b = a.slice();
//=> a = [1,2,3,4,5], b = [1,2,3,4,5]

you can use splice, but it will destroy your original array:

var a = [1,2,3,4,5]
   ,b = a.splice(0);
//=> a = [], b = [1,2,3,4,5]

Post a Comment for "Using Splice(0) To Duplicate Arrays"