Reputation: 51937
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
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
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