[英]how can i use a for loop to count to and count by a number in javascript?
Create a program that takes two numbers - one to count to and another to determine what multiple to use to get there.创建一个接受两个数字的程序 - 一个用于计数,另一个用于确定使用哪个倍数到达那里。
Here is some sample input:这是一些示例输入:
Count to: 30 Count by: 5 Output: 5, 10, 15, 20, 25, 30
计数至:30 计数:5 Output:5、10、15、20、25、30
Count to: 50 Count by: 7 Output: 7, 14, 21, 28, 35, 42, 49
计数到:50 计数:7 Output:7、14、21、28、35、42、49
here is my trial code.这是我的试用代码。
var num1 = parseInt(prompt("Count to: ")); var num2 = parseInt(prompt("Count by: ")); for(let i = num2; i <= num1; i+num2){ } console.log(i);
You need to increase the value of i
in your loop as i+num
does not increase its value:您需要增加循环中
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); }
Use modulus operator in your loop with a conditional that checks if the modulus of the number iterated is equal to zero...在循环中使用模数运算符,并带有一个检查迭代数的模数是否等于零的条件...
Count to: 30 Count by: 5 Output: 5, 10, 15, 20, 25, 30计数至: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) } }
Count to: 50 Count by: 7 Output: 7, 14, 21, 28, 35, 42, 49计数到: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) } }
Below snippet could help you下面的片段可以帮助你
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)
Your setup was good, only the console.log
statement needs to be inside the loop to print.您的设置很好,只有
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.