简体   繁体   English

JavaScript循环迭代错误

[英]Javascript loop iteration error

The loop does not seem to iterate correctly: 该循环似乎无法正确迭代:

var selections = $("#primaryModal").find("select").not(".hidden");

for(var i = 0; i < selections.length; i++){
    console.log(selections.length);
    console.log("select");
    for(var i = 0; i < $(selection)[0].options.length; i++){
        console.log("option");
    }
}

Above is my loop and the following is the result in console: 上面是我的循环,下面是控制台中的结果:

在此处输入图片说明

What seems to be the issue here? 这里似乎是什么问题? The internal loop seems to work, but the outer loop iterates only once despite an array length of 2. 内部循环似乎起作用,但是尽管数组长度为2,但外部循环仅迭代一次。

You are using the same loop index for both loops and the variable selection is not defined. 您正在两个循环中使用相同的循环索引,并且未定义变量选择。 Try something like this: 尝试这样的事情:

var selections = $("#primaryModal").find("select").not(".hidden");

for(var i = 0; i < selections.length; i++){
    console.log(selections.length);
    console.log("select");
    for(var j = 0; j < $(selections)[i].options.length; j++){
        console.log("option");
    }
}

You are working with javascript. 您正在使用javascript。 Your code will get transformed to after variable hoisting: 您的代码将在变量提升后转换为:

var i;
for(i = 0; i < selections.length; i++){
    console.log(selections.length);
    console.log("select");
    for(i = 0; i < $(selection)[0].options.length; i++){
        console.log("option");
    }
}

which means you are not having two different variables in different scopes. 这意味着您在不同的范围内没有两个不同的变量。 You should rather go with Robert Fines suggestion and change the variable name so that your code will work like and you do not have any side-effects. 您应该选择Robert Fines的建议,并更改变量名称,这样您的代码才能正常工作,并且没有任何副作用。

var i, j; 
for(i = 0; i < selections.length; i++){
    console.log(selections.length);
    console.log("select");
    for(j = 0; j < $(selections)[i].options.length; j++){
        console.log("option");
    }
}

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

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