有人可以解释为什么FOR和WHILE循环在Javascript中有不同的输出

时间:2014-08-24 20:01:24

标签: javascript

我正在学习javascript,使用循环我遇到了这个问题。 写入while循环以完成for循环的操作,但令我惊讶的是输出不同。感谢...

for (var i = 1; i < 4; i++){
    console.log(i);
}

// output -> 1 2 3

var j = 1;
while (j < 4){
    console.log(j);
    j += 1;
}
// output -> 1 2 3 4

1 个答案:

答案 0 :(得分:0)

要获得一次性错误,您需要在输出之前将循环更改为增量。

var j = 0;
while (j < 4){
    j += 1;
    console.log(j);
}
// output -> 1 2 3 4

注意:这不是问题的答案,似乎已经修复了。但是因为代码被呈现,它被发布为答案而不是评论,因此可以轻松阅读代码。

一次性的典型例子是。

var j = 0;
while (j < 4){
    console.log(++j);
}

在某些情况下使用j ++可能会发生这些增量需要特别注意,这就是为什么许多人更喜欢j + = 1语法。

var j = 0;
while (j++ < 4){
    console.log(j);
}
// outputs 1 2 3 4 the problem is the comparison takes place before j is incremented.