如何使用JavaScript将数组添加到数组中

时间:2018-09-10 12:15:44

标签: javascript

如何在下面的JavaScript中实现此目标。我尝试在MDN上搜索它,但找不到任何方法。

let a, b
let allNumbers = []

for (a = 10; a < 60; a = a + 10) {
    for (b = 1; b <= 3; b++) {
        allNumbers.push(a + b)
    }
}

所需结果是allNumbers数组中的一个数组:

[[11,12,13], [21,22,23], [31,32,33], [41,42,43], [51,52,53]]

7 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

只需在外循环中创建一个临时数组并将元素从内循环推入其中,在内循环完成后,将临时数组推入主循环中即可:

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

答案 2 :(得分:2)

您必须使用一个 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);

您可以使用ES6功能应用简短版本。

allNumbers = []
for (a = 10; a < 60; a = a + 10) {
    allNumbers.push([...Array(3)].map((_, i) => i + a + 1))
}
console.log(allNumbers);

答案 3 :(得分:2)

您可以尝试:

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

答案 4 :(得分:1)

您必须创建一个新数组,并在第二个循环中向其添加元素,然后在第二个循环后将该数组添加至最后一个数组。

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)

答案 5 :(得分:1)

您需要在循环内声明第二个数组。如下所示:

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

答案 6 :(得分:0)

只需创建一个数组并将新数组推入int NTLM

allNumbers