Merging arrays is a fairly common occurrence. I remember when I worked a lot with PHP I would use array_merge()
all the time. I found myself merging arrays often when handling form submission.
合并数组是很常见的事情。 我记得当我大量使用PHP时,会一直使用array_merge()
。 我发现自己在处理表单提交时经常合并数组。
JavaScript has a simple, native function for merging arrays (concat
) but it produces a new array. Since JavaScript vars are passed by reference, concat
may mess up a reference. If you want to merge a second array into an existing first array, you can use this trick:
JavaScript具有用于合并数组的简单本机函数( concat
),但它会生成一个新数组。 由于JavaScript变量是通过引用传递的,因此concat
可能会使引用混乱。 如果要将第二个数组合并到现有的第一个数组中,可以使用以下技巧:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
Array.prototype.push.apply(array1, array2);
console.log(array1); // is: [1, 2, 3, 4, 5, 6]
Using an Array.prototype
method, push
in this case, allows you to merge the second array into the first. The alternative is iterating through the second array and using push
on the first array. This shortcut is niiiiiiiiiice!
在这种情况下,使用Array.prototype
方法push
可以将第二个数组合并到第一个数组中。 另一种方法是遍历第二个数组并在第一个数组上使用push
。 此快捷方式很简单!