문제

HTML

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

I can't seem to understand how this while statement deletes all the nodes in the above list. Can someone please explain?

JavaScript

while(myList.firstChild) {
    myList.removeChild(myList.firstChild)
};
도움이 되었습니까?

해결책

Read while

enter image description here

HTML

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

js code

while(myList.firstChild) // loop will run while myList has a firstChild
    {myList.removeChild(myList.firstChild)
};

Run time

1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.

Now HTML

<ul id="myList">
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

Run

2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.

Now HTML

<ul id="myList">
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

Run

3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.

Now HTML

<ul id="myList">
   <li>Item 4</li>
</ul>

Run

4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.

Now HTML

<ul id="myList">
</ul>

Run

js code will not run as there is no first child in myList. While loop condition fails.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top