Home > Web Front-end > JS Tutorial > body text

Javascript copy array implementation code_Basic knowledge

WBOY
Release: 2016-05-16 18:41:07
Original
1214 people have browsed it

1. Wrong implementation
Many people may directly use the equal sign to assign values:

Copy the code The code is as follows:

var array1 = new Array("1","2","3");
var array2;
array2 = array1;
array1.length = 0;
alert(array2); //returns empty

This approach is wrong because javascript is divided into primitive types and reference types (similar to java and c#). Array is a reference class
type. array2 gets a reference, so modifications to array1 will affect array2.
2. Use slice()
You can use slice() to copy, because slice() also returns an array.
Copy code The code is as follows:

var array1 = new Array("1","2 ","3");
var array2;
array2 = array1.slice(0);
array1.length = 0;
alert(array2); //Return 1, 2, 3

3. Use concat()
Note that concat() returns not the Array of the calling function, but a new Array, so you can use this to copy.
Copy code The code is as follows:

var array1 = new Array("1","2 ","3");
var array2;
array2 = array1.concat();
array1.length = 0;
alert(array2); //Return 1, 2, 3

4. 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">



Array Test












in IE8 Both passed the test under FF3.0 and FF3.0
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!