请解释此javaScript代码如何删除所有节点 HTML
阅读 HTML请解释此javaScript代码如何删除所有节点 HTML,javascript,html,while-loop,removechild,Javascript,Html,While Loop,Removechild,阅读 HTML while(myList.firstChild) { myList.removeChild(myList.firstChild) }; 1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it. 2nd time while loop run firstChild is <li>Item 2</li> --&
while(myList.firstChild) {
myList.removeChild(myList.firstChild)
};
1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.
2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.
3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.
4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.
运行时
while(myList.firstChild) // loop will run while myList has a firstChild
{myList.removeChild(myList.firstChild)
};
第一次循环运行时,第一个子项是项1 -->代码运行并将其删除。
现在使用HTML
while(myList.firstChild) {
myList.removeChild(myList.firstChild)
};
1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.
2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.
3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.
4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.
- 项目2
- 项目3
- 项目4
跑
第二次,循环运行firstChild是项2 -->代码运行并删除它。
现在使用HTML
while(myList.firstChild) {
myList.removeChild(myList.firstChild)
};
1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.
2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.
3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.
4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.
- 项目3
- 项目4
跑
当循环运行firstChild是第3项时,3次运行并删除它。
现在使用HTML
while(myList.firstChild) {
myList.removeChild(myList.firstChild)
};
1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.
2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.
3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.
4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.
- 项目4
跑
第四次,循环运行firstChild是项4 -->代码运行并删除它。
现在使用HTML
while(myList.firstChild) {
myList.removeChild(myList.firstChild)
};
1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.
2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.
3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.
4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.
跑
js代码不会运行,因为在
myList
中没有第一个子项。While循环条件失败。它是这样工作的,While循环将一直执行,直到myList
有第一个子项为止。在循环中,你移除每个第一个孩子,这样下一个就成为第一个孩子。当myList.firstChild
变为空时,它将继续执行,直到所有内容都被删除为止。它是falsy
,因此不再运行循环。这很有帮助。循环将删除节点的第一个子节点–removeChild
–myList.firstChild,直到该节点不再有第一个子节点(因此也不再有子节点)。