【发布时间】:2021-07-01 11:31:35
【问题描述】:
我偶然发现了一个我以前从未遇到过的案例。我有一个数组数组,每个数组里面都有严重的对象或者里面什么都没有。我使用这些对象来生成一些 HTML,并且一切正常,除非我尝试处理空数据(一个内部没有对象的数组)。我正在考虑遍历它们,如果我得到一个空数组来创建特定的 HTML,但我似乎无法处理它......当我这样解释时可能听起来很混乱,所以我会留下代码 sn -p 自言自语
const theGrandArray = [
[
{id:1},
{id:12},
{id:13}
],
[
{id:2},
{id:22},
{id:23}
],
[], // this is the array I want to handle
[
{id:4},
{id:42},
{id:43}
]
]
const theUl = document.getElementById('theUl')
for(let i = 0; i < theGrandArray.length; i++ ){
for(let k = 0; k < theGrandArray[i].length; k++){
if(!theGrandArray[i][k].id){
console.log('ahaaa!')
}
let liElement = document.createElement('li')
liElement.innerText = theGrandArray[i][k].id
theUl.appendChild(liElement)
}
}
<ul id="theUl"></ul>
【问题讨论】:
-
不清楚是什么问题;如果你想处理一个空的嵌套数组检查它的长度,如果
0做一件事,> 0做你现在正在做的事情(或者你需要做的任何事情)。 -
它不起作用,因为
k < theGrandArray[i].length对于空数组始终为假。theGrandArray[i].length是0和0 < 0是假的。 -
只是一个建议,使用
forEach循环可能会帮助您更清楚地查看并进行相应的调试
标签: javascript html arrays object