【问题标题】:how can i use a for loop to count to and count by a number in javascript?如何使用 for 循环在 javascript 中对数字进行计数和计数?
【发布时间】:2020-11-23 04:32:36
【问题描述】:

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

这是一些示例输入:

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

【问题讨论】:

  • i+num2 -> i += num2
  • 另外,console.log(i) 需要在循环内。

标签: javascript arrays function for-loop


【解决方案1】:

您的设置很好,只有 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);
}

【讨论】:

    【解决方案2】:

    下面的sn-p可以帮助你

    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)

    【讨论】:

    • 这很好,我一直遇到功能问题,但这个很清楚
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      在您的循环中使用模数运算符和一个条件来检查迭代数字的模数是否等于零...

      计数到:30 计数:5 输出: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 输出:7、14、21、28、35、42、49

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-27
        • 2022-12-20
        • 2014-04-10
        • 2022-10-02
        • 2022-01-21
        • 2020-05-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多