3 回答

TA贡献1807条经验 获得超9个赞
更好的方法是将todoList.childElementCountfirst 存储在一个新变量中,并在 的终止条件中使用该变量for-loop。
或者,如果您不想存储todoList.childElementCount在新变量中,则:
for(let i = todoList.childElementCount-1; i>=0 ; i--){
console.log(i);
todoList.children[0].remove();
}

TA贡献1809条经验 获得超8个赞
todoList.children[0]与todoList.firstChild
while(todoList.children[0] !=null){
todoList.children[0].remove();
}
查找 todolist 是否有一个孩子,如果有,则将其删除。
for(let i = 0 ; i<todoList.childElementCount ; i++){
console.log(i);
todoList.children[0].remove();
}
每次查找有多少个孩子,然后删除第一个孩子。因此,它不是那么高效。

TA贡献1934条经验 获得超2个赞
如果代码是:
let initialChildCount = todoList.childElementCount;
for(let i = 0 ; i < initialChildCount; i++){
console.log(i);
todoList.children[0].remove();
}
在您的代码中,您不断减少,todoList.childElementCount因此循环结束得更快
添加回答
举报