For example, this example:
Copy Code code as follows:
var arr = ["One", "two", "Three"];
var arrto = arr;
ARRTO[1] = "Test";
Document.writeln ("Original value of the array:" + arr + "<br/>");//export: Original value of the array: One,test,three
Document.writeln ("New value of array:" + Arrto + "<br/>");//export: New value for array: One,test,three
Such direct assignment as above is a shallow copy, many times, this is not the result we want to get, in fact, we want the value of arr is unchanged, is not it?
Method One: JS's slice function
Copy Code code as follows:
For the slice function of the array object,
Returns a section of an array. (still an array)
Arrayobj.slice (start, [end])
Parameters
Arrayobj
Required option. An Array object.
Start
Required option. The starting element of the part specified in Arrayobj is the zero-based subscript.
End
Options available. The end element of the part specified in Arrayobj is the zero-based subscript.
Description
The slice method returns an Array object that contains the specified portion of the arrayobj.
The slice method is copied to the element specified by end, but does not include the element. If start is negative, it is the length + start processing, where length is the size 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 is copied to the ending of arrayobj. If End appears before start, no elements are copied into the new array.
Example:
Copy Code code as follows:
var arr = ["One", "two", "Three"];
var Arrtoo = arr.slice (0);
ARRTOO[1] = "Set Map";
Document.writeln ("Original value of the array:" + arr + "<br/>");//export: Original value of the array: One,two,three
Document.writeln ("New value of array:" + Arrtoo + "<br/>");//export: New value for array: One,set Map,three
Method Two: Concat method of JS
Copy Code code as follows:
The Concat () method is used to connect two or more arrays.
This method does not change an existing array, but merely returns a copy of the connected array.
Grammar
Arrayobject.concat (Arrayx,arrayx,......, Arrayx)
Description
Returns a new array. The array is generated by adding all the Arrayx parameters to the Arrayobject. If the argument for the concat () operation is an array, then the element in the array is added, not the array.
var arr = ["One", "two", "Three"];
Example:
Copy Code code as follows:
var arrtooo = Arr.concat ();
ARRTOOO[1] = "Set Map to";
Document.writeln ("Original value of the array:" + arr + "<br/>");//export: Original value of the array: One,two,three
Document.writeln ("New value of array:" + arrtooo + "<br/>");//export: New value for array: One,set MAP to,three