在javascript中使用for循环

时间:2016-04-13 15:48:27

标签: javascript html loops for-loop

我需要编写将首先输入的程序作为' i'而这个循环需要去 直到第一次输入小于或等于第二次输入。 我写的但似乎不起作用:

function provjeri() {

    var i  = document.getElementById('prvi').value;
    var b = document.getElementById('drugi').value;
    var c = "";

    for (; parseInt(i) <= parseInt(b)  ; i+=2) {
        c+=i ;
    }

    document.getElementById('rez').innerHTML = parseInt(c);
}

4 个答案:

答案 0 :(得分:1)

获取值时

parseInt()。另外,使用c=0c=""被视为字符串,新值将同步到c

&#13;
&#13;
function provjeri() {
  var i = parseInt(document.getElementById('prvi').value);
  var b = parseInt(document.getElementById('drugi').value);
  var c = 0;
  
  for (; i <= b  ; i+=2) {
    c+=i ;
  }
  document.getElementById('rez').innerHTML = parseInt(c);	
}
&#13;
<input id='prvi' />
<input id='drugi' />
<button onclick='provjeri()'>Calc</button><br>
<span id='rez'></span>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以这样做

var k = 0;
var ival = parseInt(i);
var bval = parseInt(v);

for (k = ival; k <= bval; k += 2) {
   c += k;
}

答案 2 :(得分:0)

这应该是这样的:

function provjeri() {
    var i  = parseInt(document.getElementById('prvi').value);
    var b = parseInt(document.getElementById('drugi').value);
    var c = 0;
    while(i <= b){
       c += i;
       i += 2;
    }
    document.getElementById('rez').innerHTML = c;
}

答案 3 :(得分:0)

我想,你正在寻找这个:

function provjeri() {
    var i = document.getElementById('prvi').value;
    var b = document.getElementById('drugi').value;
    var c = 0; // needs to be a number
    i = parseInt(i, 10);
    b = parseInt(b, 10);

    for (; i <= b; i += 2) {
        c += i;
    }
    document.getElementById('rez').innerHTML = c;
}
<input id='prvi'></input>
<input id='drugi'></input>
<button onclick='provjeri()'>call function</button><br>
<span id='rez'></span>