繁体   English   中英

如何使用 for 循环对 javascript 中的数字进行计数和计数?

[英]how can i use a for loop to count to and count by a number in javascript?

创建一个接受两个数字的程序 - 一个用于计数,另一个用于确定使用哪个倍数到达那里。

这是一些示例输入:

计数至:30 计数:5 Output:5、10、15、20、25、30

计数到:50 计数:7 Output: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);

您需要增加循环中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); }

在循环中使用模数运算符,并带有一个检查迭代数的模数是否等于零的条件...

计数至:30 计数:5 Output:5、10、15、20、25、30

 let targetNumber = 30; for(let i = 1; i <= targetNumber; i++){ if( i % 5 === 0){ console.log(i) } }

计数到:50 计数:7 Output:7、14、21、28、35、42、49

 let targetNumber = 50; for(let i = 1; i <= targetNumber; i++){ if( i % 7 === 0){ console.log(i) } }

下面的片段可以帮助你

 function count(countTo, countBy) { const arr = [] for (let i = countBy; i <= countTo; i += countBy) { arr.push(i) } console.log(arr.join(', ')) } count(30, 5) count(50, 7)

您的设置很好,只有console.log语句需要在循环内才能打印。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM