Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用for循环计算从0到1的整数_Javascript_For Loop_Count - Fatal编程技术网

Javascript 使用for循环计算从0到1的整数

Javascript 使用for循环计算从0到1的整数,javascript,for-loop,count,Javascript,For Loop,Count,我有一个0-5的html选择列表。我从列表中选择一个数字,例如4,我想让程序吐出5。因为0,1,2,3,4是5个数字。目前,我的循环只是将数字相加到15。我的for循环中的逻辑有问题 document.getElementById('go').onclick = function () { var topValue = document.getElementById('number').value; topValue = parseFloat(topValue); number = 0; for

我有一个0-5的html选择列表。我从列表中选择一个数字,例如4,我想让程序吐出5。因为0,1,2,3,4是5个数字。目前,我的循环只是将数字相加到15。我的for循环中的逻辑有问题

document.getElementById('go').onclick = function () {
var topValue = document.getElementById('number').value;
topValue = parseFloat(topValue);
number = 0;
for (n = 0; n <= topValue; n++) {
    number = number + n;
};
document.getElementById('result').value = number;
};
document.getElementById('go').onclick=function(){
var topValue=document.getElementById('number').value;
topValue=parseFloat(topValue);
数字=0;

对于(n=0;n我不知道我是否正确理解了您的疑问,但我会尽力帮助您:

这是因为您正在将变量“n”的值添加到变量“number”

for循环接收3个内容(基本/简化):

  • 它的起始值
  • 其最大值(通常在条件为真时停止的位置)
  • 其“速度”(计数器将增加或减少的大小)
topValue为4时循环的执行:

  • 执行1:number=(number+n)=>(0+0)=0
  • 执行2:number=(number+n)=>(0+1)=1
  • 执行3:number=(number+n)=>(1+2)=3
  • 执行4:number=(number+n)=>(3+3)=6
  • 执行5:number=(number+n)=>(6+4)=10
  • 如果您只想计算零(包括)和topValue之间存在多少个数字,只需将其放入循环中:

    number++;
    

    如果我理解正确,您不需要循环。它总是比所选数字多一个

    document.getElementById('go').onclick = function () {
        var topValue = document.getElementById('number').value;
    
        topValue = parseFloat(topValue);
    
        document.getElementById('result').value = number + 1;
    };
    

    我的for循环中的逻辑出了什么问题
    的确切意思是什么?你能提供一个最小的可复制示例(plunker/jsfiddle)吗?也许我读错了,但你不是只想要
    topValue+1