關(guān)于Uncaught(in?promise)TypeError:?list?is?not?iterable報錯解決
最近在項目中遇到 Uncaught (in promise) TypeError: list is not iterable 報錯,雖然不影響代碼運行,但是看著報錯感覺有點難受,試試能不能解決它

看了很多篇文章,都是說使用 Object.keys() 可以解決問題
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() 看看,代碼運行之后

因為 Object.keys() 傳入的是 null 和 undefined 時就會出現(xià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)
}
}
}
},添加條件判斷之后,確實能夠解決,代碼正常運行,也不報錯了,很好
仔細琢磨一下,感覺加條件判斷的話是不是可以不使用 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)
}
}
}
},代碼運行之后,功能正常也不報錯,確實是可以的
總結(jié)一下:
使不使用 Object.keys() 其實都可以,主要的關(guān)鍵點在于添加條件使得 list 在不為null或undefined時執(zhí)行代碼,如果為了保險起見可以添加 Object.kes() ,看項目需求吧
到此這篇關(guān)于Uncaught(in promise)TypeError: list is not iterable報錯解決的文章就介紹到這了,更多相關(guān)Uncaught(in promise)TypeError內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue路由的模塊自動化與統(tǒng)一加載實現(xiàn)
這篇文章主要介紹了Vue路由的模塊自動化與統(tǒng)一加載實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06

