简单的JavaScript循环错误答案

时间:2014-04-20 18:55:48

标签: javascript loops

var v = [2, 4, 5];
var out = 0;
for (var i = 0; i < v.length; i++) {
    if(v[i] % 2 == 0){
        out++;
    } else {
        out--;
    }

}

我得到1作为答案,我不明白为什么它是2!

我的方法:

for i = 0:
v[0]%2 = 2 % 2 = 0 so proceed with out++
out = 0 + 1 = 1

for i = 1:
v[1]%2 = 4 % 2 = 0 so proceed with out++
out = 1 + 1 = 2

for i = 2:
v[2]%2 = 5 % 2 != 0 so proceed with out--
i.e. out = 2 - 1 = 1

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

使用函数..

function toReturn(array){
  var out = 0;
  for (var i = 0; i < array.length; i++) {
    if(array[i] % 2 == 0){
        out++;
    } else {
        out--;
    }
  }

  return out;
}

称之为toReturn([2,4,5])

答案 1 :(得分:0)

试试这个,你会在每一步看到输出......最后是1

var v = [2, 4, 5];
var out = 0;
for (var i = 0; i < v.length; i++) {
    if(v[i] % 2 === 0){ out++; } 
    else { out--; }
    console.log(out);
}
// final value again
console.log(out);
// result
// 1
// 2
// 1
// 1

// PS. you can also use a ternary (just for info)
out += v[i] % 2 ? -1 : 1;
祝你好运 :)