将数组项复制到另一个数组中 [英] Copy array items into another array

查看:55
本文介绍了将数组项复制到另一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JavaScript 数组 dataArray,我想将它推入一个新数组 newArray.除了我不希望 newArray[0] 成为 dataArray.我想将所有项目推入新数组:

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 items into the new array:

var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...

甚至更好:

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
);

所以现在新数组包含各个数据数组的所有值.是否有诸如 pushValues 之类的速记,这样我就不必遍历每个单独的 dataArray,逐个添加项目?

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 items one by one?

推荐答案

使用 concat 函数,如下所示:

Use the concat function, like so:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayA.concat(arrayB);

newArray 的值将是 [1, 2, 3, 4] (arrayA and arrayB保持不变;concat 为结果创建并返回一个新数组).

The value of newArray will be [1, 2, 3, 4] (arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

这篇关于将数组项复制到另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆