Append an array to another array in JavaScript

This question is an exact duplicate of:
How to append an array to an existing JavaScript Array?

How do you append an array to another array in JavaScript?

Other ways that a person might word this question:

  • Add an array to another
  • Concat / Concatenate arrays
  • Extend an array with another array
  • Put the contents of one array into another array

I spent some time looking for the answer to this question. Sometimes the simplest ones like these are the hardest to find answers to, so I am adding the question here hopefully with plenty of key words and phrases as per this blog post. Please feel free to answer this question with any other helpful information or edit the key words and phrases below.

191850 次浏览

如果希望修改原始数组而不是返回新数组,请使用 .push()..。

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

我使用 .apply同时推送数组 23的各个成员。

或者..。

array1.push.apply(array1, array2.concat(array3));

要处理大型数组,可以批处理。

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}

如果您经常这样做,那么创建一个方法或函数来处理它。

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);


Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});

像这样使用它:

array1.pushArrayMembers(array2, array3);

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);


Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});


var array1 = ['a','b','c'];
var array2 = ['d','e','f'];
var array3 = ['g','h','i'];


array1.pushArrayMembers(array2, array3);


document.body.textContent = JSON.stringify(array1, null, 4);