繁体   English   中英

JavaScript中意外的嵌套循环行为

[英]Unexpected nested loop behavior in javascript

我正在实现某种排序,但是遇到了一些意外行为:

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
        }
}

实际上,j始终为2。为什么j进入for循环时不设置为i?

这是jsfiddle: http : //jsfiddle.net/w2kK9/3/

您使用了错误的分号:

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

其余部分被解释为与环已被执行之后运行的块(当j == 2 )。

拿出来,它工作正常。

您的嵌套for循环不执行任何操作:

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

删除半冒号。

暂无
暂无

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

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