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

我正在创建一个导航列表,每当将新的部分元素添加到页面时,该列表就会动态填充。我首先创建了一个空数组,其目的是通过对其应用 forLoop 来连续接收页面上添加的内容。


这是 JavaScript 代码


    var list= document.getElementById('navbar__list'); 


let myArray= []; //Create an empty array

for( 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) 返回空数组,导航栏上依次不显示任何项目在网页上。


白衣染霜花
浏览 52回答 1
1回答

手掌心

在数组上添加或删除元素时,不应迭代数组。一般来说,这是一件有风险的事情,因为它取决于编程语言,而且也很难理解。在这种情况下,最好使用while或do-while循环。如果你想留在 for 循环中,你可以简单地添加一个中断条件。for ( let i = 0; i < myArray.length; i++){&nbsp; &nbsp; let triggerSection= document.getElementById( 'section' + ( 1 + i ));&nbsp; &nbsp; if ( triggerSection === null ) break;&nbsp; &nbsp; ...}相反,更好的循环终止条件可能是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) {&nbsp; &nbsp; i++;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript