2013-05-06 38 views
1

我有一个嵌套的for循环未没有完成/退出 它被陷在第二循环:为什么嵌套for循环没有完成?

for (var j = 0; next.className != "rfccs" && next !== null; j++) 

当“未来”为空,只被卡住。

我的代码:

var filtertypes = document.getElementsByClassName("rfccs"); // filtertypes is an array of all filter type headers 
var next = null; // placeholder for the next sibling element 
var tout = document.getElementById("testout"); //test 
tout.innerHTML = "init "; //test 

for (var i = 0; i < filtertypes.length; i++) { 
    filtertypes[i].className += " fhead" + i; // adds a unique class to every filter type header div 
    var filtertype = filtertypes[i]; // sets filtertype to the current filter type header 
    next = filtertype.nextElementSibling; // gets the next sibling 

    for (var j = 0; next.className != "rfccs" && next !== null; j++) { // adds the same class name to all filters in the same filter type 
     next.className += " ftype" + i; 
     next.innerHTML += i; 
     next = next.nextElementSibling; 
     tout.innerHTML += "i = " + i + "; j = " + j + "///"; 
     if (next == null) { 
      tout.innerHTML += "DONE"; 
     } 
    } 
    tout.innerHTML += "~~~~"; 
} 

我知道我的跟踪/调试代码是非常的混乱。

这里是Fiddle

+2

如果''next''是''空'',你的代码将会失败,因为第一件事是它会检查属性''next.className''。你需要交换支票。 – mzedeler 2013-05-06 18:17:14

+0

@DerekThomasTran:除了“mzdeler”说的外。这里是[**逻辑运算符**](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators)的MDN文档的链接,它很好地解释了这些操作员进行检查。我希望你会发现这有助于防止类似的未来问题:) – Nope 2013-05-06 19:14:07

回答

1
var next = null; 
next.className; // TypeError: Cannot read property 'className' of null 

检查.className

next !== null && next.className !== "rfccs" // false if null 

此外,作为任何HTML元素truthy通过逻辑运算符之前一定要检查null,你可以跳过全部为!== null

next && next.className !== "rfccs" // falsy if `next` falsy 
0

的解决方案是

for (var j = 0; next != null && next.className != "rfccs"; j++) 

如果next is nullnext.className会失败,因此JavaScript的循环

看,如果这是你所期望的 http://jsfiddle.net/wJBJL/6/