JavaScript joins multiple arrays without concat to solve them

Source: Internet
Author: User
Tags arrays joins

This article mainly introduces the use of concat to solve JavaScript to connect multiple arrays, the need for friends can refer to the following

The first method is the well-known concat, but this method has a certain that the method does not change the existing array, but only returns a copy of the connected array. If you just want to add the elements of a new array to an existing array, we have to reassign it, but there is a waste of resources.    To put it simply, we want to allocate new memory space for the newly created array, and point the arr1 back to the new memory address, then the original memory array, hey, it depends on the browser can be properly recycled.  The following example: The code is as follows: var arr1 = [1,2,3];    var arr1 = Arr1.concat ([4,5]);    So are there any good ways to avoid this resource drain?  Here you can use JavaScript native apply method to achieve, first look at the following code: code as follows: Var arr1= [1,2,3];    Arr1.push.apply (arr1,[4,5]);    This is done, this method cleverly applied the characteristics of the Apply method (the second parameter is multiple of the array type) freed the push method, the push method from itself can only pass multiple values into an array can be passed, the above code is equivalent to the code is as follows: Arr1.push (4,5); So arr1 is still the arr1, only the memory is rewritten, no redirects and unnecessary memory overflows.
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.