for循环嵌套数组输出

时间:2019-09-07 22:52:51

标签: javascript nested

我必须做的一部分工作是编写一个程序,该程序可以计算最多10个乘法表并将结果存储在数组中。第一个条目格式示例为“ 1 x 1 = 1”。 我想我为嵌套的for循环编写了正确的代码,但不确定如何正确输出它。

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

3 个答案:

答案 0 :(得分:1)

您可以使用模板字符串,并且可以不使用数组而仅遍历数组中的数字(以与遍历索引相同的方式):

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

答案 1 :(得分:1)

var multiple = [];
var first = 1;
var last = 10;

for (var i = first; i <= last; i++) {
  for (var j = first; j <= last; j++) {
    multiple.push(i + " x " + j + " = " + (i*j));
    console.log(multiple[multiple.length-1]);
  }
}

答案 2 :(得分:1)

不确定ES6是否属于您的课程,因此这是在有和没有模板文字的情况下如何做的事情

// Create the arrays that you want to multiply

var numOne = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var numTwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Create a function that accepts both arrays as arguments
function multiply(arr1, arr2) {
  var products = [];
  for (var i = 0; i < arr1.length; i++) {
    for (var j = 0; j < arr2.length; j++) {
        //Here we are using template literals to format the response, so that the program will show you the inputs and calculate the answer
      products.push(`${arr1[i]} X ${arr1[j]} = ${arr1[i] * arr2[j]}`); 
      /* If ES6 is outside of the curriculum, the older method for formatting would be like this:
        products.push(arr1[i] + " X " + arr2[j] + " = " + arr1[i]*arr2[j])
      */
    }
  }
  console.log(products);
  return products;
}

// Call the second function example
multiply(numOne, numTwo);