[英]Add array inside array in Javascript
How do I push array into a new Array.如何将数组推送到新数组中。 For example
例如
var arr = ['one','two','three'];
var newArr = [];
Now I want newArr[0] = ['one','two','three']
现在我想要
newArr[0] = ['one','two','three']
I have tried using push
function but it pushes all the elements of arr
into newArr
.我尝试使用
push
函数,但它将arr
所有元素推送到newArr
。 I want to push the entire arr
as it is in newArr
我想推动整个
arr
就像在newArr
var arr = ['one','two','three'];
var newArr = [];
newArr.push(arr); //<-- add entire original array as first key of new array
Others have answered, so I guess your question is not really clear.其他人已经回答了,所以我想你的问题不是很清楚。
As you put your question, first and only element of newArray should be the arr array, then you use当你提出你的问题时,newArray 的第一个也是唯一的元素应该是 arr 数组,然后你使用
newArr.push(arr);
as Mitya and Tiij7 said.正如 Mitya 和 Tiij7 所说。
However, maybe you meant you want to join (concat) 2 arrays in a new array?但是,也许您的意思是要在新数组中加入(连接)2 个数组? Then you would use:
然后你会使用:
var arr3 = [].concat(arr, newArr);
or或者
var arr3 = [...arr, ...newArr];
Or you just wanted to clone the initial array?或者你只是想克隆初始数组? Then use
然后使用
var newArr = [...arr];
You can write:你可以写:
newArr[0] = ['one','two','three'];
And this will work.这将起作用。 Or use variable:
或者使用变量:
newArr[0] = arr;
Also, array methods push
or unshift
will the same way in your situation work:此外,数组方法
push
或unshift
将在您的情况下以相同的方式工作:
newArr.push(arr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.