Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using splice(0) to duplicate arrays

Tags:

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.

like image 998
frenchie Avatar asked Aug 22 '12 12:08

frenchie


People also ask

How do you copy an array using splice?

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.

Does splice work on arrays?

splice() The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice() .

Does splice affect the original array?

The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object. The splice() method changes the original array and slice() method doesn't change the original array.

How do you make a shallow copy of an array?

Array Clone – Shallow Copy In Java, to create clone of array, you should use clone() method of array. It creates a shallow copy of array. Cloning always creates shallow copy of array. Any change (in original array) will be reflected in cloned array as well.


1 Answers

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.

like image 77
Sirko Avatar answered Oct 20 '22 05:10

Sirko