I. Error implementation
Many people may directly assign values using equal signs:
CopyCode The Code is as follows: var array1 = new array ("1", "2", "3 ");
VaR array2;
Array2 = array1;
Array1.length = 0;
Alert (array2); // The returned result is null.
This is wrong, because JavaScript divides the original type into reference types (similar to Java and C ). Array is a reference class
Type. Array2 gets a reference, so the modification to array1 will affect array2.
Ii. Use slice ()
You can use slice () for replication because slice () returns an array.Copy codeThe Code is as follows: var array1 = new array ("1", "2", "3 ");
VaR array2;
Array2 = array1.slice (0 );
Array1.length = 0;
Alert (array2); // returns 1, 2, and 3
3. Use Concat ()
Note that Concat () does not return the array that calls the function, but a new array, so you can use this to copy.Copy codeThe Code is as follows: var array1 = new array ("1", "2", "3 ");
VaR array2;
Array2 = array1.concat ();
Array1.length = 0;
Alert (array2); // returns 1, 2, and 3
Iv. Test Copy code The Code is as follows: <! Doctype HTML public "-// W3C // dtd html 4.01 // en" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<Head>
<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>
</Head>
<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>
</Html>
Both IE8 and ff3.0 pass the test.