简体   繁体   中英

Unexpected nested loop behavior in javascript

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/

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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