Implementation code of an array in Javascript

Source: Internet
Author: User

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 );

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.