Javascript clone an array of implementation code

  • 2020-03-30 00:48:17
  • OfStack

In 2008, a company JS interview question, the position is javascript engineer (to Google)

When the interviewer asked me how to clone an array, I thought that js Object had no clone method and Java Object had.

So how do you get a new array?

I replied: a loop pushes the elements of the source array into the new array. This is the easiest way, but clearly not the answer the interviewer is looking for.

Finally, let me know: slice method using Array. Here's an example:


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

 
ary2[0] = 10; 
console.log(ary2); 
console.log(ary); 


Related articles: