最近在項(xiàng)目中遇到 Uncaught (in promise) TypeError: list is not iterable 報(bào)錯(cuò),雖然不影響代碼運(yùn)行,但是看著報(bào)錯(cuò)感覺(jué)有點(diǎn)難受,試試能不能解決它

看了很多篇文章,都是說(shuō)使用 Object.keys() 可以解決問(wèn)題
formatTree2(list) {
for (const item of Object.keys(list)) {
if (list[item].children && list[item].children.length === 0) {
delete list[item].children
} else {
this.formatTree2(list[item].children)
}
}
},
就先使用 Object.keys() 看看,代碼運(yùn)行之后

因?yàn)?Object.keys() 傳入的是 null 和 undefined 時(shí)就會(huì)出現(xiàn)這種問(wèn)題,如何解決呢,試試加條件判斷
formatTree2(list) {
if (list) {
for (const item of Object.keys(list)) {
if (list[item].children && list[item].children.length === 0) {
delete list[item].children
} else {
this.formatTree2(list[item].children)
}
}
}
},
添加條件判斷之后,確實(shí)能夠解決,代碼正常運(yùn)行,也不報(bào)錯(cuò)了,很好
仔細(xì)琢磨一下,感覺(jué)加條件判斷的話(huà)是不是可以不使用 Object.keys() 呢,值得一試
formatTree2(list) {
if (list) {
for (const item of list) {
if (item.children && item.children.length === 0) {
delete item.children
} else {
this.formatTree2(item.children)
}
}
}
},
代碼運(yùn)行之后,功能正常也不報(bào)錯(cuò),確實(shí)是可以的
總結(jié)一下:文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-514373.html
使不使用 Object.keys() 其實(shí)都可以,主要的關(guān)鍵點(diǎn)在于添加條件使得 list 在不為null或undefined時(shí)執(zhí)行代碼,如果為了保險(xiǎn)起見(jiàn)可以添加 Object.kes() ,看項(xiàng)目需求吧文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-514373.html
到了這里,關(guān)于解決 Uncaught (in promise) TypeError: list is not iterable 報(bào)錯(cuò)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!