如何在数组内部动态生成数组?

时间:2018-11-28 11:57:43

标签: javascript arrays

如何在数组内创建数组。例如,假设 MainArray [] 是我根据

等条件定义的数组
if(something happen){
then push object into array inside MainArray
In other iteration make new array and push elements into that inside 
MainArray
}

希望您能回答这个问题。我们将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

推入另一个数组内的数组与推入任何数组没有什么不同。 假设您有一个数组arr

let arr = [[1],[2]];

arr[0].push(3);

console.log(arr)//[[1,3],[2]];

根据评论,您需要[ [{},{}], [{}], [{},{},{}] ]。 假设我们从此开始。 如果您arr[0].push({hello:"World"});会得到 [ [{},{},{hello:"World"}], [{}], [{},{},{}] ]

答案 1 :(得分:1)

希望这就是您想要的:

// pushes an array at the end of MainArray
MainArray.push([]); 
// pushes elements into that newly created array inside MainArray
MainArray[MainArray.length-1].push('whatever u want...'); 
相关问题