frenchie
frenchie

Reputation: 51937

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 elements from the initial array.

In the console, when I run this code:

var ArrayA = [];
var ArrayB = [];

ArrayA.push(1);
ArrayA.push(2);

ArrayB = ArrayA.splice(0);

alert(ArrayA.length);

the alert shows 0. What am I doing wrong with .splice(0)??

Thanks for your insight.

Upvotes: 25

Views: 29312

Answers (3)

KooiInc
KooiInc

Reputation: 122906

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]

Upvotes: 5

Imp
Imp

Reputation: 8609

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.

Upvotes: 7

Sirko
Sirko

Reputation: 74046

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.

Upvotes: 54

Related Questions