简体   繁体   English

Javascript代码进入无限循环

[英]Javascript code goes into infinite loop

the following code goes into infinite loop and a crash in the webpage I need to know what's wrong with it? 以下代码进入无限循环,并且网页崩溃了,我需要知道这是怎么回事?

    for (var i = 0; i < 2; i+1) {
            for (var j = i; j < 8; j + 2) {
                console.log(arr[j].Qu);
            }
            console.log(arr[i]);
        }

i+1 doesn't update i's value, therefor, the i always has value 1, as it takes 0+1 in every run, thus never being > 2 and never ending You need to change it with i++, like this i + 1不会更新i的值,因此,i始终为1,因为每次运行都需要0 + 1,因此永不> 2且永无止境,您需要使用i ++对其进行更改,例如

for (var i = 0; i < 2; i++) {

Also, as @Xufox points out, udpate your J loop with 另外,正如@Xufox指出的那样,使用

for (var j = i; j < 8; j += 2) {

i+1 is not an assign operation, that's why you need to assign the value urself. i + 1不是分配操作,这就是为什么您需要自己分配值的原因。 i++ and j+=2 translate to i++j+=2转换为

i = i+1;
j= j+2;

and the result of the righthand operation is self-assigned to the variable 右手操作的结果将自赋给变量

Value is not assigned back to variable. 值未分配回变量。

 for (var i = 0; i < 2; i+=1) { // i++
            for (var j = i; j < 8; j+=2) {
                console.log(arr[j].Qu);
            }
            console.log(arr[i]);
        }

i+1 doesn't modify i value. i+1不会修改i值。 You could write instead i++ . 您可以改为编写i++

Similarly, j + 2 doesn't update j. 同样, j + 2不会更新j。 You should write j += 2 . 您应该写j += 2

Here is the corrected code : 这是更正的代码:

for (var i = 0; i < 2; i++) {
    for (var j = i; j < 8; j += 2) {
        console.log(arr[j].Qu);
    }
    console.log(arr[i]);
}

 for (var i = 0; i < 2; i+=1) { for (var j = i; j < 8; j+= 2) { console.log(arr[j]); } console.log(arr[i]); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM