Home >Web Front-end >JS Tutorial >Implementation code for cloning an array in Javascript_javascript skills

Implementation code for cloning an array in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:291186browse

JS interview questions from a company in 2008, the position is javascript engineer (going to Google)

The interviewer asked me how to clone an array. At that time, I thought about it. The Object of js does not have a clone method, but the Object of java does.

Then how do you get a new array?

I answered at the time: Use a loop to push the elements of the source array into the new array in sequence. This is the simplest method, but obviously not the answer the interviewer wants.

Finally tell me: use the slice method of Array. The example is as follows:

Copy code The code is as follows:

var ary = [1,2,3 ];//Source array
var ary2 = ary.slice(0);//Clone a new array
console.log(ary2);

/* Changing ary2 will not affect ary, indicating that they are indeed two arrays rather than references
* If there are two references, changing either one is an operation on the same array
*/
ary2[0] = 10;
console.log(ary2);
console.log(ary);
Statement:
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