Javascript concatenates multiple arrays without concat

  • 2020-03-30 02:27:40
  • OfStack

The first method is known as concat, but it is certain that the method does not change the existing array and only returns a copy of the concatenated array.

If we just want to add the elements of a new array to an existing array, we have to re-assign them, which is a little bit of a waste of resources. Simply put, we need to allocate new memory space for the newly created array, and point arr1 back to the new memory address, so the original array in memory will be recycled by the browser.

The following cases:
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 implement, first look at the following code:
var arr1= [1,2,3]; 

That's it. This method cleverly USES the attributes of the apply method (the second parameter is multiple of the array type) to free up the push method, which itself can only pass multiple values to an array, and the code above is equivalent to

So arr1 is still arr1, just a memory rewrite, no redirects and no unnecessary memory leaks.

Related articles: