javascript - 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)返回为空数组,导航栏上依次不显示任何项目在网页上。
解决方案
在数组上添加或删除元素时,不应迭代数组。这通常是一件有风险的事情,因为它取决于编程语言并且也很难理解。在这种情况下,最好使用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++;
}
推荐阅读
- javascript - 打字稿无法导入 lodash
- antlr4 - 无法将 CPP14 加载为词法分析器或解析器
- angular - 除了 Angular 9 中的 LocalStorage 之外,在哪里存储当前用户?
- reactjs - 在 React 中加载更多按钮
- python - 连接列表 PYTHON
- node.js - Excel 中 CSV 文件的特殊字符问题,Sheetjs 为 utf8 CSV 文件添加 BOM
- javascript - Google Apps Script PropertiesService - 因不可靠的执行记录和编辑器调试而感到困惑
- azure-logic-apps - 逻辑应用部署 - 找不到集成帐户:工作流必须与集成帐户关联才能使用工作流运行操作
- wagtail - 如何在 Wagtail 中检索属于具有收藏权限的组的用户的图像?
- python - 使用 django 显示 404 错误处理页面