亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

這兩個代碼有什么區別?

這兩個代碼有什么區別?

慕哥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 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號