1

我有一个未完成/退出的嵌套 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 += "~~~~";
}

我知道我的跟踪/调试代码真的很乱。

这是小提琴

4

2 回答 2

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

检查null前先检查一下.className

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

此外,由于任何HTMLElement对逻辑运算符都是真实的,因此您可以完全跳过!== null

next && next.className !== "rfccs" // falsy if `next` falsy
于 2013-05-06T18:17:27.557 回答
0

The solution is

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

if next is null next.className will fail and hence javascript loop

see if this is what you expect http://jsfiddle.net/wJBJL/6/

于 2013-05-06T18:19:05.337 回答