Home  >  Article  >  Web Front-end  >  Javascript connects multiple arrays without concat to solve the problem_javascript skills

Javascript connects multiple arrays without concat to solve the problem_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:54:291059browse

The first method is the well-known concat, but one thing about this method is that it will not change the existing array, but will only return a copy of the connected array.

If we just want to add the elements of a new array to the existing array, we have to reassign it, which is actually a little waste of resources. To put it simply, we need to allocate new memory space for the newly created array and redirect arr1 to this new memory address. So what about the original array in memory? Hehe, it depends on whether the browser can recycle it correctly.

The following example:

Copy the code The code is as follows:

var arr1 = [1,2,3];
var arr1 = arr1.concat([4,5]);

So do we have any good way to avoid this resource consumption?

Here you can use Javascript’s native apply method to achieve this. First look at the following code:
Copy the code The code is as follows :

var arr1= [1,2,3];
arr1.push.apply(arr1,[4,5]);

That’s it Done, this method cleverly uses the characteristics of the apply method (the second parameter is multiple array types) to liberate the push method. The push method can only pass multiple values ​​​​from itself to an array. The above code is actually It is equivalent to
Copy code The code is as follows:

arr1.push(4,5) ;

In this way, arr1 is still the same arr1, but the memory has been rewritten, without redirection and unnecessary memory overflow.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn