作者:5257wals_220 | 来源:互联网 | 2023-01-15 15:05
IhaveajavascriptarraydataArraywhichIwanttopushintoanewarraynewArray.ExceptIdontw
I have a Javascript array dataArray
which I want to push into a new array newArray
. Except I don't want newArray[0]
to be dataArray
. I want to push in all the values into the new array:
我有一个Javascript数组dataArray我想把它推入一个新的数组newArray。除非我不想让newArray[0]成为dataArray。我想把所有的值都推到新数组中:
var newArray = [];
newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...
or even better:
或者更好的是:
var newArray = new Array (
dataArray1.values(),
dataArray2.values(),
// ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);
So now the new array contains all the values of the individual data arrays. Is there some shorthand like pushValues
available so I don't have to iterate over each individual dataArray, adding the values 1 by 1?
现在,新数组包含了各个数据数组的所有值。是否有一些类似pushValues的简写方式,这样我就不必遍历每个单独的dataArray,并将值1加1?
13 个解决方案
565
Provided your arrays are not huge (see caveat below), you can use the push()
method of the array to which you wish to append values. push()
can take multiple parameters so you can use its apply()
method to pass the array of values to be pushed as a list of function parameters. This has the advantage over using concat()
of adding elements to the array in place rather than creating a new array.
如果您的数组不是很大(请参阅下面的说明),您可以使用您希望添加值的数组的push()方法。push()可以使用多个参数,因此您可以使用它的apply()方法来传递值的数组作为函数参数的列表。这比使用concat()将元素添加到数组中而不是创建一个新数组具有优势。
However, it seems that for large arrays (of the order of 100,000 members or more), this trick can fail. For such arrays, using a loop is a better approach. See https://stackoverflow.com/a/17368101/96100 for details.
然而,对于大型数组(100,000个成员或更多的成员)来说,这个技巧可能会失败。对于这样的数组,使用循环是更好的方法。有关详细信息,请参阅https://stackoverflow.com/a/17368101/96100。
var newArray = [];
newArray.push.apply(newArray, dataArray1);
newArray.push.apply(newArray, dataArray2);
You might want to generalize this into a function:
你可能想把它归纳成一个函数:
function pushArray(arr, arr2) {
arr.push.apply(arr, arr2);
}
... or add it to Array
's prototype:
…或者将其添加到Array的原型中:
Array.prototype.pushArray = function(arr) {
this.push.apply(this, arr);
};
var newArray = [];
newArray.pushArray(dataArray1);
newArray.pushArray(dataArray2);
... or emulate the original push()
method by allowing multiple parameters using the fact that concat()
, like push()
, allows multiple parameters:
…或者模拟原始的push()方法,允许多个参数使用concat()和push()这样的事实,允许多个参数:
Array.prototype.pushArray = function() {
this.push.apply(this, this.concat.apply([], arguments));
};
var newArray = [];
newArray.pushArray(dataArray1, dataArray2);
Here's a loop-based version of the last example, suitable for large arrays and all major browsers, including IE <= 8:
这里是最后一个示例的循环版本,适用于大型数组和所有主流浏览器,包括IE <= 8:
Array.prototype.pushArray = function() {
var toPush = this.concat.apply([], arguments);
for (var i = 0, len = toPush.length; i