Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

javascript - 将数组项复制到另一个数组中(Copy array items into another array)

I have a JavaScript array dataArray which I want to push into a new array newArray .

(我有一个JavaScript数组dataArray ,我想将其推入一个新的数组newArray 。)

Except I don't want newArray[0] to be dataArray .

(除了我不希望newArray[0]成为dataArray 。)

I want to push in all the items into the new array:

(我想将所有项目推入新数组:)

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

(有没有类似pushValues简写,所以我不必迭代每个dataArray ,逐个添加项目?)

  ask by bba translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the concat function, like so:

(使用concat函数,如下所示:)

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

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

(newArray的值为[1, 2, 3, 4]arrayAarrayB保持不变; concat为结果创建并返回一个新数组)。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...