I. Error implementation
Many people may directly assign values using equal signs:
VaR Array1 = New Array ( " 1 " , " 2 " , " 3 " );
VaR Array2;
Array2 = Array1;
Array1.length = 0 ;
Alert (array2 ); // Return Blank
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.
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.
VaR Array1 = New Array ( " 1 " , " 2 " , " 3 " );
VaR Array2;
Array2 = Array1.concat ();
Array1.length = 0 ;
Alert (array2 ); // Returns 1, 2, and 3.
Iv. Test
Code
<! 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; charsets = 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.