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



我正在创建一个导航列表,每当向页面添加新的section元素时,就会动态填充该列表。我首先创建了一个空数组,其目的是通过对其应用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(的额外元素;未捕获的类型错误:无法读取null的属性"getAttribute">

当删除等号以使结束条件如下(i<myArray.length(时,错误不再显示,但创建的(myArray(返回为空数组,依次在网页的导航栏上不显示任何项目。

在添加或删除数组元素时,不应该对数组进行迭代。这通常是一件有风险的事情,因为它取决于编程语言,也很难理解。在这种情况下,最好使用whiledowhile循环。

如果你想保持你的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++;
}

最新更新