For example:
var arr = ["One", "Two","Three"];
var arrto = arr;
arrto[1] = "test";
document.writeln("The original value of the array: " arr "< br />");//Export: The original value of the array: One,test,Three
document.writeln("The new value of the array: " arrto "
");//Export: New value of array: One,test,Three
The direct assignment method like the above is a shallow copy. Many times, this is not the result we want. In fact, what we want is that the value of arr remains unchanged, right?
Method 1: js slice function
For array The slice function of the object,
returns a segment of an array. (Still an array)
arrayObj.slice(start, [end])
Parameters
arrayObj
Required. An Array object.
start
Required. The starting element of the portion specified in arrayObj is a zero-based index.
end
Optional. The end element of the portion specified in arrayObj is the zero-based index.
Description
The slice method returns an Array object, which contains the specified part of arrayObj. The
slice method copies up to, but not including, the element specified by end. If start is negative, treat it as length start, where length is the length of the array. If end is negative, it is treated as length end, where length is the length of the array. If end is omitted, the slice method copies until the end of arrayObj. If end appears before start, no elements are copied to the new array.
Example:
var arr = ["One","Two","Three"];
var arrtoo = arr.slice(0);
arrtoo[1] = "set Map";
document. writeln("The original value of the array: " arr "
");//Export: The original value of the array: One,Two,Three
document.writeln("The new value of the array: " arrtoo "
");//Export: New value of array: One,set Map,Three
Method 2: js concat method
concat( ) method is used to concatenate two or more arrays.
This method does not change the existing array, but only returns a copy of the connected array.
Syntax
arrayObject.concat(arrayX,arrayX,...,arrayX)
Description
Returns a new array. The array is generated by adding all arrayX parameters to arrayObject. If the argument to concat() is an array, then 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("The original of the array Value: " arr "
");//Export: The original value of the array: One,Two,Three
document.writeln("The new value of the array: " arrtooo "
");//Export: New value of the array: One,set Map To,Three