javascript - 乘法表打印到控制台

标签 javascript

所以我的目标是在控制台中打印乘法口诀表。这段代码有效,但只有在我尝试将其放入函数中时才会有效。

我已将循环末尾的 console.log 替换为返回(见下文),然后它只给我 3 行输出。我希望这是足够清楚的,这是我第一次发帖。

  const multiplicationTable = function(maxValue) {



    for (let i = 0; i < 0; i++){
        // This is shown to verify which value is the one on the 
         multiplication table with each line
        //console.log(""+i);
        // then it clears the variable tableLine with each new line
        let tableLine = "";

        for (let j = 1; j <= maxValue; j++) {
            // It will add the results to a string each time
         tableLine += ""+(i*j)+" ";

        }  return tableLine; //and display each line in the console

      } 
    } 



    console.log(multiplicationTable(1));
    console.log(multiplicationTable(5));
    console.log(multiplicationTable(10));

    //1
    //
    //1 2 3 4 5
    //2 4 6 8 10
    //3 6 9 12 15
    //4 8 12 16 20
    //5 10 15 20 25 
    //
    //1 2 3 4 5 6 7 8 9 10
    //2 4 6 8 10 12 14 16 18 20
    //3 6 9 12 15 18 21 24 27 30
    //4 8 12 16 20 24 28 32 36 40
    //5 10 15 20 25 30 35 40 45 50
    //6 12 18 24 30 36 42 48 54 60
    //7 14 21 28 35 42 49 56 63 70
    //8 16 24 32 40 48 56 64 72 80
    //9 18 27 36 45 54 63 72 81 90
    //10 20 30 40 50 60 70 80 90 100

最佳答案

当您在函数内部使用return 时,它会立即退出该函数并且不会继续其余的处理。

您需要做的是使用另一个常量(例如table)来存储您的tableLine。在处理结束时,您返回 table 值。

我已经修改了你的代码,你可以在下面看到它以供引用。 您将能够获得与预期相同的输出。

function multiplicationTable(maxValue) {
  let table = "";

  for (let i = 1; i <= maxValue; i++) {
    let tableLine = "";
    for (let j = 1; j <= maxValue; j++) {
     tableLine += ""+(i*j)+" ";
    }

    tableLine += "\n";
    table += tableLine;
  } 

  return table;
}

关于javascript - 乘法表打印到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796676/

相关文章:

javascript - 如何从 jquery 调用 Controller ?

javascript - 具有小图形的 Neo4J 在 Ubuntu 16.04 上使用大量内存

Javascript 在重新加载时保留水平滚动条位置

javascript - 将相交的多边形合并为单个多边形

javascript - 将对象插入 mongoDB,["object Object"] 已保存

javascript - 验证 $index 并设置样式

javascript - 从 Google calculator api 的 JSON 字符串中获取值

javascript - 不能在 Neo4j 属性中使用美元符号 ($)

javascript - Jquery 1.11.1 - 下载文件和附加回调

javascript - 如何将滚动位置设置为选中单选按钮的级别?