使用JavaScript合并数组

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 。 此快捷方式很简单!

翻译自: https://davidwalsh.name/merge-arrays-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值