简体   繁体   中英

JavaScript For Loop Skipping items in an Array

I'm a little confused on what is happening here. I have an html unordered list and I am to sort it out into 3 separate lists based on an attribute value. This is very basic, I'm aware but I ran into something peculiar with a for loop and its increment.

[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>

Then sort it out into these lists

[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>

I currently have this

        ///////////////////////////////////
        // 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!

But when I change my for loop to add increments (Like I have always been doing)

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

I end up with something like this

Does Not Work

Now I've also tried using

for (var i in ulList) {

and I get the same results as it not working

Can anyone help me understand what I am obviously missing? Thank you!

As you've probably noticed, appendChild() moves the element to a new position in a document. getElementsByTagName() returns an array-like object, which is live, ie it is automatically updated when you add or remove elements to/from its "scope".

You can fix your loop by decrementing i by one every time you append from ulList .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM