我有一個嵌套的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
如果''next''是''空'',你的代碼將會失敗,因爲第一件事是它會檢查屬性''next.className''。你需要交換支票。 – mzedeler 2013-05-06 18:17:14
@DerekThomasTran:除了「mzdeler」說的外。這裏是[**邏輯運算符**](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators)的MDN文檔的鏈接,它很好地解釋了這些操作員進行檢查。我希望你會發現這有助於防止類似的未來問題:) – Nope 2013-05-06 19:14:07