javascript - 如何使用 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);
解决方案
您需要增加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);
}
推荐阅读
- json - 将 XML 转换为 Json Angular
- mysql - 如果不存在冲突,如何使用 mysql 仅返回记录?
- reactjs - 在帐户集合 Firebase 中注册时设置用户 ID
- javascript - 从多个下拉菜单中过滤选择
- python - 如何在 Python 的一张图中绘制速度剖面和边界厚度剖面?
- java - 有没有办法在不重复整数的情况下将 int[] 复制到另一个 int[] ?
- ruby - Ruby 的 Dir.glob 不遵循符号链接
- c# - 无法从 OverlapCircleAll 返回的 Collider2D 列表中检索游戏对象名称
- javascript - 我如何应用回调来获取方法中的 http 响应
- django - 如何在 Windows 上使用 nssm 为 django 应用程序创建服务