In the course of a project, we will sometimes encounter a situation where we need to combine two arrays into one. Such as:

Var a = [1, 2, 3]; Var b = (4 and 6);

There are two arrays a and b, and the requirement is to merge the two arrays into one. Concat JS’s Array object provides a method called concat() that concatenates two or more arrays and returns the result.

var c = a.concat(b); / / c = [6];

There is a problem here. When concat concatenates arrays A and B, the data in both arrays remains unchanged and a new array is returned. This will cause a lot of memory waste when we need to do multiple array merges, so this method is definitely not the best.

2. For loop

The idea is to traverse one array and add all the elements of that array in turn to the other. Directly on the code:

for(var i in b){

a.push(b[i]);

} This can solve the memory waste in the first solution, but it has another problem: ugly! Apply (obj,argv), where argv is an array, func. Apply (obj,argv). So we can take advantage of this and go straight to the code:

a.push.apply(a,b);

A. Rush will be merged through all elements of the array by calling the apply method of this function instance and passing in b as an argument.

This might be a little confusing, but we could view b as [4,5,6], and it would look like this:

Amy polumbo ush. Apply (a, (4 and 6));

Then the above operation is equivalent to:

Amy polumbo ush (4 and 6);

That should be clear!

In addition, there are two small issues to note:

1) The above three merging methods do not consider which of the two arrays A and B has the smaller length.

A good idea is to predetermine which of the two arrays a and b is larger, and then combine the larger array with the smaller array. This reduces the number of operations on the elements of the array!

2) Sometimes we don’t want the original array (a, b) to change, so we have to use concat.