javascript merge two arrays

In the development process, we often encounter the need to merge the two arrays into an array of circumstances arise.

var arr1 = [1, 2, 3 ];
 var arr2 = [4, 5, 6 ]; 

// the merged arr2 arr1 and [1, 2, 3, 4, 5, 6]

We summarize here the method to merge two arrays in JavaScript.

for loop through the array

This approach is the simplest, most easy to achieve.

var arr3 = [];

// 遍历arr1
for (var i = 0; i < arr1.length; i++) {
    arr3.push(arr1[i]);
}

// 遍历arr2
for (var j = 0; j < arr2.length; j++) {
    arr3.push(arr2[j]);
}

console.log(arr3); // [1,2,3,4,5,6]

It may be used to achieve further enhanced for loop or forEach () method.

The for loop is hardly any problem in this way, but many people will seek to streamline the programming despise this way (Tan Shou).

concat () method

Array object in JavaScript provides a concat () method, is to connect two or more arrays, and returns a new array.

var arr3 = arr1.concat(arr2);

console.log(arr3);
// [1,2,3,4,5,6]

Note that, concat () method does not change the original array, but returns a new array. In this way, when we need multiple arrays combined, it will result in wasted memory.

apply () method

apply the method function has a feature that func.apply (obj, argv), argv is an array. So we can use that.

arr1.push.apply(arr1, arr2);

This function call arr1.push instance apply () method, while the arr1, arr2 passed as a parameter, so arr1.push this method will loop through all the elements of an array arr2 arr1 and achieve the effect of the merger.

Simple to understand, the above code can be seen:

arr1.push(4, 5, 6);

This way only one line of code to solve the problem, can be very 6 a.

to sum up

The above three methods in routine use and in fact there is no difference, but in addition to pay attention to two minor problems:

1. The above three kinds of combined method is not considered when exemplified through two arrays whose original length is smaller, it is good practice in advance to determine which two original larger arrays, arrays with small and large arrays, this can be reducing the number of array elements operations, improve the efficiency of the code.

2. Sometimes we neither want the original array (arr1, arr2) change, do not want to manually add a variable, then you can only use the concat () method has.

 

" Life has owned all brilliant, lonely may eventually need to use to repay. "

Guess you like

Origin www.cnblogs.com/yanggb/p/11463434.html