0

I'm implementing a sort, and I've run into some unexpected behavior:

var searches = ['beta', 'alpha'];
var i = 0; j = 0;

for(i = 0; i < searches.length; i++){
        min = i;

        // first time through, i = 0
         alert(i); 
        for(j = i; j<searches.length; j++);
        {
            // first time through j = 2. If i = 0, how does j = 2?
             alert(j); 
            // .. sort code
        }
}

In fact, j is always 2. Why isn't j being set to i when it enters the for loop?

Here's the jsfiddle: http://jsfiddle.net/w2kK9/3/

2 Answers 2

6

You have a misplaced semi-colon:

for (j = i; j < searches.length; j++); // <--

The rest is interpreted as a block that runs after the loop has executed (when j == 2).

Take that out and it works fine.

Sign up to request clarification or add additional context in comments.

Comments

2

Your nested for loop isn't doing anything:

for(j = i; j<searches.length; j++); // <- Your for loop proceeds only on this line.

Remove the semi colon.

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.