[英]How to add arrays into an array in JavaScript
How could I achieve this below in JavaScript. 我如何在JavaScript中实现以下目标。 I tried searching for it on MDN but couldn't find any method for it.
我尝试在MDN上搜索它,但找不到任何方法。
let a, b
let allNumbers = []
for (a = 10; a < 60; a = a + 10) {
for (b = 1; b <= 3; b++) {
allNumbers.push(a + b)
}
}
The desired outcome is an array inside the allNumbers
array: 所需的结果是
allNumbers
数组内的allNumbers
数组:
[[11,12,13], [21,22,23], [31,32,33], [41,42,43], [51,52,53]]
how about this 这个怎么样
var a, b
var allNumbers = []
for (a = 10; a < 60; a = a + 10) {
var part = [];
for (b = 1; b <= 3; b++) {
part.push(a + b)
}
allNumbers.push(part)
}
Just create a temporary Array in the outer loop and push the elements from the inner loop into it, after the inner Loop is finished, push the temporary array in the main one: 只需在外循环中创建一个临时数组并将元素从内循环推入其中,在内循环完成后,将临时数组推入主循环中:
let a, b let allNumbers = [] for (a = 10; a < 60; a += 10) { let someNumbers = []; for (b = 1; b <= 3; b++) { someNumbers.push(a + b) } allNumbers.push(someNumbers) } console.log(JSON.stringify(allNumbers))
You have to use one second array
. 您必须使用一秒钟的
array
。
let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { second = []; for (b = 1; b <= 3; b++) { second.push(a + b); } allNumbers.push(second) } console.log(allNumbers);
You can apply a shorted version using ES6
features. 您可以使用
ES6
功能应用简短版本。
allNumbers = [] for (a = 10; a < 60; a = a + 10) { allNumbers.push([...Array(3)].map((_, i) => i + a + 1)) } console.log(allNumbers);
You can try: 你可以试试:
const result = Array(5).fill(1).map((a, i) => Array(3).fill(1).map((a, j) => +`${i+1}${j+1}`)); console.log(JSON.stringify(result));
You have to create a new array an add the element to it in the second loop and the add this array to the final one after the second loop. 您必须创建一个新数组,然后在第二个循环中向其添加元素,然后在第二个循环后将该数组添加至最后一个数组。
let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { data = [] for (b = 1; b <= 3; b++) { data.push(a + b) } allNumbers.push(data) } console.log(allNumbers)
You need to declare a second array inside your loop. 您需要在循环内声明第二个数组。 Like following:
如下所示:
let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { var tempArray = []; for (b = 1; b <= 3; b++) { tempArray.push(a + b) } allNumbers.push(tempArray); } console.log(allNumbers);
Just create an array and push the new array int allNumbers
: 只需创建一个数组并将新数组推入int
allNumbers
:
...
let c = []
for (b = 1; b <= 3; b++) {
c.push(a + b)
}
allNumbers.push(c)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.