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.
So 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. Examples are as follows:
Copy the code code 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);