为了账号安全,请及时绑定邮箱和手机立即绑定

这两个代码有什么区别?

这两个代码有什么区别?

慕哥9229398 2022-12-08 15:33:04
while(todoList.children[0] !=null){    todoList.children[0].remove();}for(let i = 0 ; i<todoList.childElementCount ; i++){    console.log(i);    todoList.children[0].remove();}我有一个列表,其中有 5 个元素。我想从中删除元素。如果我尝试达到列表元素计数,它会毫无问题地给出 5 个值。当我使用 while 循环时,它可以工作,但 for 循环只运行 3 次。
查看完整描述

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();

}


查看完整回答
反对 回复 2022-12-08
?
海绵宝宝撒

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();

}

每次查找有多少个孩子,然后删除第一个孩子。因此,它不是那么高效。


查看完整回答
反对 回复 2022-12-08
?
撒科打诨

TA贡献1934条经验 获得超2个赞

如果代码是:


let initialChildCount = todoList.childElementCount;

for(let i = 0 ; i < initialChildCount; i++){

    console.log(i);

    todoList.children[0].remove();

}

在您的代码中,您不断减少,todoList.childElementCount因此循环结束得更快


查看完整回答
反对 回复 2022-12-08
  • 3 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号