First, error implementation
Many people may directly use the equal sign to assign a value:
Copy Code code as follows:
var array1 = new Array ("1", "2", "3");
var array2;
Array2 = array1;
array1.length = 0;
alert (array2); return to NULL
This is wrong because JavaScript is divided into primitive types and reference types (similar to Java, C #). Array is a reference class
Type. Array2 gets a reference, so the modification of array1 affects array2.
Ii. use of slice ()
You can use slice () for replication because the slice () return is also an array.
Copy Code code as follows:
var array1 = new Array ("1", "2", "3");
var array2;
Array2 = Array1.slice (0);
array1.length = 0;
alert (array2); Return 1, 2, 3
Iii. use of concat ()
Note that concat () does not return a call to the function's array, but rather a new array, so you can use this to replicate.
Copy Code code as follows:
var array1 = new Array ("1", "2", "3");
var array2;
Array2 = Array1.concat ();
array1.length = 0;
alert (array2); Return 1, 2, 3
Four, test
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>array test</title>
<script type= "Text/javascript" >
var array1;
var array2;
function Clone1 () {
Array1 = new Array ("1", "2", "3");
Array2 = array1;
array1.length = 0;
alert (array2);
}
function Clone2 () {
Array1 = new Array ("1", "2", "3");
Array2 = Array1.slice (0);
array1.length = 0;
alert (array2);
}
function Clone3 () {
Array1 = new Array ("1", "2", "3");
Array2 = Array1.concat ();
array1.length = 0;
alert (array2);
}
</script>
<body>
<input type= "button" value= "Clone1" onclick= "Clone1 ()"/><br/>
<input type= "button" value= "Clone2" onclick= "Clone2 ()"/><br/>
<input type= "button" value= "Clone3" onclick= "Clone3 ()"/><br/>
</body>
Passed the test under IE8 and FF3.0