JavaScript For循环跳过数组中的项目

时间:2014-05-30 20:46:16

标签: javascript for-loop html-lists auto-increment for-in-loop

我对这里发生的事情感到有些困惑。我有一个html无序列表,我将根据属性值将其分类为3个单独的列表。这是非常基本的,我知道但是我遇到了一个特殊的for循环及其增量。

[this is code provided to be worked with]
 <ul id="queue">
        <li want="coffee">Phil(html)</li>
        <li want="coffee">Sandy(html)</li>
        <li want="sandwich">Enrique(html)</li>
        <li want="coffee">Joe(html)</li>
        <li want="muffin">Alex(html)</li>
        <li want="chili">Zoe(html)</li>
        <li want="sandwich">Bahamut(html)</li>
        <li want="timbits">Rydia(html)</li>     
    </ul>

然后将其分类到这些列表中

[this is code provided to be worked with]
<section id="sandwiches">
        <h1>Sandwich line</h1>
        <ul id="sandwich-line">
        </ul>
    </section>


    <section id="coffee">
        <h1>Coffee line</h1>
        <ul id="coffee-line">
        </ul>
    </section>


    <section id="everything-else">
        <h1>Everythin else line</h1>
        <ul id="everything-else-line">
        </ul>
    </section>

我目前有这个

        ///////////////////////////////////
        // HTML Queue
        ///////////////////////////////////

        // Grab the Queue element and 
        var ulList = document.getElementById('queue').getElementsByTagName('li');

        for(var i = 0; i < ulList.length;){
            // this finds out what they "want" based on the attribute
            var ulOrder = ulList[i].getAttribute("want");

            // To organize the line we can use if statements
            if (ulOrder === "coffee"){
                coffeeLine.appendChild(ulList[i]);

            } else if (ulOrder === "sandwich"){
                sandLine.appendChild(ulList[i]);
            } else {
                elseLine.appendChild(ulList[i]);
               }
           }

Which works!

但是当我改变我的for循环以增加增量时(就像我一直在做的那样)

 for (var i = 0; i < ulList.length; i++){

我最终得到了类似的东西

Does Not Work

现在我也尝试使用

for (var i in ulList) {

我得到的结果与不工作相同

任何人都可以帮助我理解我明显缺少的东西吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

您可能已经注意到,appendChild() 元素移动到文档中的新位置。 getElementsByTagName()返回一个类似于数组的对象,它是实时的,即当你向&#34;范围&#34;添加或删除元素时它会自动更新。

每次从i追加时,您都可以通过将ulList递减1来修复循环。