2013-05-06 99 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/