JavaScript For循环跳过数组中的项

JavaScript For Loop Skipping items in an Array

本文关键字:数组 For 循环 JavaScript      更新时间:2023-09-26

我对这里发生的事情有点困惑。我有一个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]);
               }
           }

工作!

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

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

我最终得到了这样的东西

不工作

现在我也试着使用

for (var i in ulList) {

和我得到相同的结果,因为它不工作

谁能帮我理解我显然错过了什么?谢谢你!

您可能已经注意到,appendChild() 元素移动到文档中的新位置。getElementsByTagName()返回一个类似数组的对象,它是活的,也就是说,当你从它的"作用域"中添加或删除元素时,它会自动更新。

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