Implementation code of an array in Javascript
This article mainly introduces the implementation code of an array in Javascript. For more information, see.
Javascript interview questions for a company in, job as a javascript Engineer (go to google)
The interviewer asked me how to clone an array. At that time, I thought that js objects do not have the clone method, and java objects do.
How can we get a new array?
I then replied: Use a loop to push the elements of the source array to the new array in sequence. This is the simplest method, but it is clearly not the answer that the interviewer wants.
Finally, let me know: Use the slice Method of Array. Example:
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 does not affect ary. It indicates that it is indeed two arrays instead of references.
* If there are two references, changing either of them is to operate on the same array.
*/
Ary2 [0] = 10;
Console. log (ary2 );
Console. log (ary );