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

标签: javascripthtmlarraysfor-loop

解决方案


在数组上添加或删除元素时,不应迭代数组。这通常是一件有风险的事情,因为它取决于编程语言并且也很难理解。在这种情况下,最好使用whiledo-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++;
}

推荐阅读