I have array:
var array = ["a", "b", "c"];
I need save this array to another variable
var save = array;
Now I need splice from save
first index but when I try it, the index is removed from both arrays.
var array = ["a", "b", "c"];
var save = array;
save.splice(0, 1);
console.log(array);
console.log(save);
arraycopy() method. arraycopy can be used to copy a subset of an array.
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.
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.
The copyOfRange() method is used to copy the elements of the specified range of the original array into clone array. The syntax of the copyOfRange() method is as follows: public static int[] copyOfRange(int[] original, int from, int to)
You need to copy the array using Array#slice
otherwise save
holds the reference to the original array(Both variables are pointing to the same array).
var save = array.slice();
var array = ["a", "b", "c"];
var save = array.slice();
save.splice(0, 1);
console.log(array);
console.log(save);
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