首页 > 解决方案 > 如何使用 for 循环在 javascript 中对数字进行计数和计数?

问题描述

创建一个接受两个数字的程序 - 一个用于计数,另一个用于确定要使用的倍数。

这是一些示例输入:

计数到:30 计数:5 输出:5、10、15、20、25、30

计数至:50 计数:7 输出:7、14、21、28、35、42、49

这是我的试用代码。

var num1 = parseInt(prompt("Count to: "));
var num2 = parseInt(prompt("Count by: "));
for(let i = num2; i <= num1; i+num2){

}
console.log(i);

标签: javascriptarraysfunctionfor-loop

解决方案


您需要增加i循环中的值,因为i+num不会增加其值:

// Changed the variable names to something more descriptive
// to avoid confusion on larger code bases;
var maxValue = parseInt(prompt("Count to: "));
var stepValue = parseInt(prompt("Count by: "));

// Can also be written as index += stepValue
for(let index = stepValue; index <= maxValue; index = index + stepValue) {
  // Print the current value of index
  console.log(index);  
}


推荐阅读