首页 > 解决方案 > for loops nested array output

问题描述

Part of my homework I have to write a program that calculates all multiplication tables up to 10 and store the results in an array. The first entry formatting example is "1 x 1 = 1". I think I have my code written right for the nested for loop but I'm not sure on how to output it properly.

var numOne = [1,2,3,4,5,6,7,8,9,10];
var numTwo = [1,2,3,4,5,6,7,8,9,10];
var multiple = [];
for (var i = 0; i < numOne.length; i++) {
  for (var j = 0; j < numTwo.length; j++) {
    multiple.push(numOne[i] * numTwo[j]);
    console.log(numOne[i] * numTwo[j]);
  }
}

标签: javascriptnested

解决方案


您可以使用模板字符串,并且可以在不使用数组的情况下循环遍历数组中的数字(与循环遍历索引的方式相同):

var multiple = [];
var m;

for (var i = 1; i <= 10; i++) {
  for (var j = 1; j <= 10; j++) {
    m = i * j;
    multiple.push(m);
    console.log(`${i} * ${j} = ${m}`);
  }
}


推荐阅读