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

For 循环停止条件,用于在代码运行时动态填充的数组

For 循环停止条件,用于在代码运行时动态填充的数组

白衣染霜花 2023-11-11 21:46:08
我正在创建一个导航列表,每当将新的部分元素添加到页面时,该列表就会动态填充。我首先创建了一个空数组,其目的是通过对其应用 forLoop 来连续接收页面上添加的内容。这是 JavaScript 代码    var list= document.getElementById('navbar__list'); let myArray= []; //Create an empty arrayfor( let i=0; i<=myArray.length; i++){  var triggerSection= document.getElementById('section'+(1+i)); //Call section elements one by one with id=section(1+i)  myArray.push(triggerSection); //push elements to create an array that includes all sections on the page  var sectionName= myArray[i].getAttribute('data-nav'); //Call data-nav value for each item  const newItem= document.createElement('Li'); //create li elemnt inside the document object  newItem.textContent= sectionName; //pass the data-nav value as a text to the li element  newItem.setAttribute('id','item'+(1+i));  list.appendChild(newItem); //pass the li element to the  unordered list}HTML 代码<ul id="navbar__list">      </ul><section id="section1" data-nav="Section 1" class="your-active-class"><section id="section2" data-nav="Section 2"><section id="section3" data-nav="Section 3">问题是,当设置如上所示的 for 循环的结束条件时,它会在数组末尾添加一个值为 (null) 的额外元素,并且控制台会生成该错误“ Uncaught TypeError: Cannot read property 'getAttribute'为空”当删除等号以使结束条件如下 (i<myArray.length) 时,不再显示错误,但创建的 (myArray) 返回空数组,导航栏上依次不显示任何项目在网页上。
查看完整描述

1 回答

?
手掌心

TA贡献1942条经验 获得超3个赞

在数组上添加或删除元素时,不应迭代数组。一般来说,这是一件有风险的事情,因为它取决于编程语言,而且也很难理解。在这种情况下,最好使用while或do-while循环。


如果你想留在 for 循环中,你可以简单地添加一个中断条件。


for ( let i = 0; i < myArray.length; i++){

    let triggerSection= document.getElementById( 'section' + ( 1 + i ));

    if ( triggerSection === null ) break;

    ...

}

相反,更好的循环终止条件可能是triggerSection === null,因为如果未找到元素则getElementById返回。null(https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)


因此这应该有效:


let i = 0;

while ( (let triggerSection = document.getElementById( 'section' + ( 1 + i ))) !== null) {



    i++;

}


查看完整回答
反对 回复 2023-11-11
  • 1 回答
  • 0 关注
  • 44 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信