0

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:

enter image description here

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
  • typo ? missing an s ? `$(selections)' Commented Mar 24, 2017 at 21:09
  • you are using variable i for both the loop. so your inner loop resets the i to 6 (in your case) which fails the parent condition i<2 . try mapping your inner loop with different variable Commented Mar 24, 2017 at 21:10

2 Answers 2

3

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");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Haha. Oh man, total rookie move. I know better, just seeing what I want to see I suppose. I'll definIitely leave this up for others though. It's a good example of an easily overlooked error. Thanks for the feedback.
It happens to everyone :) Glad I could be of help.
1

You are working with 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.

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");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.