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.
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.
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() .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With