Two methods for deep and shallow copies of JavaScript arrays
- 2020-03-30 02:37:45
- OfStack
Here's an example:
var arr = ["One","Two","Three"];
var arrto = arr;
arrto[1] = "test";
document.writeln(" Original value of array: " + arr + "<br />");//Export: the original value of the array: One,test,Three
document.writeln(" New value of array: " + arrto + "<br />");//Export: New value of array: One,test,Three
The direct assignment like the one above is the shallow copy, and a lot of times, that's not what we want, we want the arr to be the same, right?
Method 1: slice function of js
for array The object's slice The function,
Returns a segment of an array. (still an array)
arrayObj.slice(start, [end])
parameter
arrayObj
Will be options. a Array Object.
start
Will be options. arrayObj The starting element of the specified part in the.
end
Optional. arrayObj The end element of the specified part in
instructions
slice Method returns a Array Object that contains arrayObj The specified part of.
slice Copy the method all the way to end The element specified, but not included. if start It's negative. Let's write it as length + start Processing, here length Is the length of the array. if end If it's negative, let's write it as length + end Processing, here length Is the length of the array. If you omit end , then slice The method will copy all the way to arrayObj In the end. if end Appear in the start Previously, no elements were copied into the new array.
Example:
var arr = ["One","Two","Three"];
var arrtoo = arr.slice(0);
arrtoo[1] = "set Map";
document.writeln(" Original value of array: " + arr + "<br />");//Export: the original value of the array: One,Two,Three
document.writeln(" New value of array: " + arrtoo + "<br />");//Export: new value of the array: One,set Map,Three
Method 2: js concat method
concat() Method is used to join two or more arrays.
This method does not change the existing array, but simply returns a copy of the concatenated array.
grammar
arrayObject.concat(arrayX,arrayX,......,arrayX)
instructions
Returns a new array. The array is passed by putting all arrayX Add parameters to arrayObject Is generated in. If you want to do concat() The operation takes an array as an argument, so the elements in the array are added, not the array.
var arr = ["One","Two","Three"];
Example:
var arrtooo = arr.concat();
arrtooo[1] = "set Map To";
document.writeln(" Original value of array: " + arr + "<br />");//Export: the original value of the array: One,Two,Three
document.writeln(" New value of array: " + arrtooo + "<br />");//Export: New value of array: One,set Map To,Three