The first method is the well-known concat, but there is a certainty of this method that this method will not change the existing array, but will only return a copy of the connected array.
If we just want to add elements of a new array to an existing array, we also need to reassign it, which actually has a little waste of resources. Simply put, we need to allocate new memory space for the newly created array and point arr1 to the new memory address again. So what about the array in memory? Hehe, it depends on whether the browser can recycle it correctly.
As shown in the following example:
The code copy is as follows:
var arr1 = [1,2,3];
var arr1 = arr1.concat([4,5]);
So are there any good ways for us to avoid this resource consumption?
Here you can use Javascript's native apply method to implement it. First, look at the following code:
The code copy is as follows:
var arr1= [1,2,3];
arr1.push.apply(arr1,[4,5]);
This is done. This method cleverly uses the characteristics of the apply method (the second parameter is multiple array types) and frees the push method. The push method has changed from being able to pass multiple values by itself to being able to pass an array. The code is actually equivalent to
The code copy is as follows:
arr1.push(4,5);
In this way, arr1 is still the same arr1, but the memory has been rewritten, without redirection or unnecessary memory overflow.