在if / else语句

时间:2015-10-10 14:39:01

标签: javascript if-statement

这只是一个使用的简单乘法程序 如果/ 别的和 for循环。 从提示中重新输入正数并将其分配给num变量 for循环应该使用是打破程序。我不知道为什么它是不正确的。 ?也许你可以告诉我使用它的最佳方法     如果/     别的和     for循环。 任何帮助非常感谢。

//Array variable and counter variable

var multi = new Array();

var Counter;

//Enter a number between 1 and 12 and hold in num variable

num = prompt("Enter a number between 1 and 12");

//Check if number is less than zero
//Reenter positive number

if (num < 0) {
    var num = prompt("Enter a number greater than zero");
} 
else {
    //Number entered by user multiplied by counter value
    for (Counter = 1; Counter <= 12; Counter++) {
        multi[Counter] = num * Counter;
    }
    //Loop to display number that is being multiplied each time 
    for (Counter = 1; Counter <= 12; Counter++) {
        document.write(Counter + " x " + num + "  = " + multi[Counter] + '<br/>');
    }
}

1 个答案:

答案 0 :(得分:1)

这可以在修复代码的同时简化。

输入负数导致代码失败的原因是因为您永远不会访问else块,因此永远不会在其中运行预期的代码。

正如melpomene所建议的那样,do / while循环将为您提供良好的服务。

您也不需要2个单独的for循环,它们可以合并为一个。

var num;

do {

  // Enter a number between 1 and 12 and hold in num variable
  // Check if number is not between 1 and 12 and re-enter
  num = prompt("Enter a number between 1 and 12");

} while (num < 1 || num > 12);

// You can define your counter variable within the for loop
for (var counter = 1; counter <= 12; counter++) {

   document.write(counter + ' x ' + num + '  = ' + (num * counter) + '<br/>')

}