如何在JavaScript中打印倒数时间表

时间:2018-09-11 03:26:41

标签: javascript loops

我正尝试像照片一样反向打印此时间表,但无法确定需要更改的内容。

var digit = 9, multiplier = 9, textresult = "", result = 0;
while (digit > 0) {
    for (multiplier = 9; multiplier >= digit; multiplier--) {
      result = digit * multiplier;
        if (digit == multiplier) {
         textresult += digit + " x " + multiplier + " = " + result + " 
           <br>";}
        else {
             textresult += digit + " x " + multiplier + " = " + result + 
             "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";}
     }
     digit--;}
     strong textdocument.write(textresult);

有什么想法吗?

expected result image

2 个答案:

答案 0 :(得分:0)

digit开始计数,而不是从9开始计数。在每个内部循环中,将multiplier初始化为digit而不是9,并且类似地,用multiplier计数:

var digit = 1,
  textresult = "";
while (digit < 10) {
  for (let multiplier = digit; multiplier < 10; multiplier++) {
    const result = digit * multiplier;
    textresult += digit + " x " + multiplier + " = " + result + (multiplier === 9 ? '<br>' : "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
    }
    digit++;
  }
  document.write(textresult);

答案 1 :(得分:0)

尝试此更正

var digit = 1,
  textresult = "<pre><code>",
  max = 9;
while (digit <= max) {
  for (var multiplier = digit; multiplier <= max; multiplier++) {
    var result = digit * multiplier;
    textresult += digit + " * " + multiplier + " = " + result;
    if (10 > result) {
      textresult += " ";
    }
    if (max == multiplier) {
      textresult += "<br/>";
    } else {
      textresult += "  ";
    }
  }
  digit++;
}
textresult += "</pre></code>";
document.write(textresult);