运行循环10次

时间:2017-07-11 03:44:27

标签: javascript

我正在编写一个程序,用于计算用户输入的数字乘以2。

我意识到我需要一个for循环,以便Value将增加1并且将乘以2

问题是我想知道如何运行此循环仅10次 - 在当前它将永远运行,如果值达到50,我必须放置一个if语句来突破循环。

//prompt user to enter number
let value = prompt("Enter A number");
//user entered number will loop through while output will show multiples //of 2
for (value;; value++) {
  value2 = value * 2;
  document.write(`${value} multiply 2 -> ${value2}`);
  document.write('<br>');
  //i placed this if statement to break out of the for loop as it //will run forever
  if (value > 50) {
    break;
  }
}

2 个答案:

答案 0 :(得分:2)

您可以使用计数器变量来检查迭代次数。我猜你想在每次迭代后将值增加1。你可以这样做:

  //prompt user to enter number
    let value = prompt("Enter A number");
 //user entered number will loop through while output will show multiples //of 2
    for (var i=1;i<=10; i++) {
      value2 = value * 2;
      document.write(`${value} multiply 2 -> ${value2}`);
      document.write('<br>');
      //i placed this if statement to break out of the for loop as it //will run forever
      value++;

    }
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <!--
<script type="text/javascript" src="js.js"></script>
-->
</head>

<body></body>

</html>

答案 1 :(得分:-1)

<!DOCTYPE html>
<html>
<body>

<h2>Multiple By 2</h2>

<input type="text" id="num"/>

<button onclick="multiply()">multiply by 2</button>

<script>
function multiply() {
    var number = document.getElementById("num").value;
    for(i=1;i<11;i++){
       console.log(number*i);

    }  
}

</script>

</body>
</html>