簡體   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