In the course of our project, we sometimes encounter situations where we need to combine two numbers and become one .
Like what:
12 |
var a = [1,2,3]; var b = [4,5,6]; |
There are two arrays of a, B, and the requirement is to combine two arrays into one. Here's how:
1, Concat
The JS Array object provides a method called Concat (), joins two or more arrays, and returns the result.
1 |
var c = a.concat(b); //c=[1,2,3,4,5,6] |
Here's a question, the Concat method joins A, b two arrays, the data of A and B two arrays is unchanged, and a new array is returned. This is certainly not the best approach when we need to make multiple array merges, which can cause a lot of wasted memory.
2. For loop
The approximate idea is to iterate through one of the arrays and add all the elements in the array to the other array in turn. Directly on the code:
for (var i in B) { a.push (b[i]);}
This way of writing can solve the memory waste in the first scenario, but there is another problem: ugly! This is not unreasonable, if you can only use a single line of code to do it, not fast ~
3. Apply
The Apply method of the function has a feature, that is func.apply (OBJ,ARGV), argv is an array. So we can use this, directly on the code:
A.push.apply (A, b);
Call A.push This function instance of the Apply method, at the same time, B as a parameter passed, so A.push this method will traverse the B array of all elements, to achieve the effect of merging.
This may be a bit of a detour, and we can think of B as [4,5,6], and it becomes this:
A.push.apply (a,[4,5,6]);
Then the above operation is equivalent to:
A.push (4,5,6);
So it's clear!
In addition, there are two minor issues to note:
1) The above 3 merging methods do not take into account A, b two arrays whose length is smaller.
So it's a good idea to prejudge the size of a, b two arrays, and then use large arrays to merge decimal groups, which reduces the number of operations on array elements!
2) Sometimes we do not want the original array (a, b) to change, then we can only use concat.
JS merging two arrays in a way