带for循环的乘法表1-10

时间:2019-02-28 20:14:44

标签: javascript algorithm

我需要从1-10创建一个乘法表, 但我得到this,而我应该得到this

我在做什么错了?

let tabel = " "; 

for (a = 1; a <= 10; a++){ 

    console.log(" " + a); 
    tabel = " ";

    for (b = 1; b <= 10; b++) { 

        tabel += " " + (a * b) + " ";  
    }

    console.log(tabel);
}

1 个答案:

答案 0 :(得分:1)

您做错了很多事情,例如:

  1. 您正在写不必要的日志console.log(" " + a);,这些日志不应该在表中
  2. 您要在数字之间放置空格,而与数字包含多少符号无关。这就是为什么格式错误的原因。

对于我来说,您的代码应如下所示:

let tt = ""; 

for (a = 1; a <= 10; a++){ 

    for (b = 1; b <= 10; b++) { 

        const result = String(a * b); // Just converting result of multiplication to a sting
        tt += ' '.repeat(4 - result.length) + result; // Prepending result with appropriate number of spaces
    }
    tt += '\n'; // Adding linewrap (in Windows systems maybe you should use \r\n instead of \n)
}
console.log(tt);