報錯類型一般為兩種
對象類型
對象沒有數(shù)據(jù)的時候為undefined 這個時候訪問內(nèi)部內(nèi)容就會報錯
舉個例子
正常情況 對象有值的時候
var obj={name:‘張三’,age:18}
#此時對象有數(shù)據(jù)訪問不會報錯
console.log(obj.name)
1
2
3
對象沒值的時候
var obj={}
console.log(obj.name)
#就會報錯 Uncaught SyntaxError: Unexpected token ‘.’
#表示空對象{}不能使用.
1
2
3
4
對象為undefined的時候
#本地數(shù)據(jù)為后端獲取的 直接賦值 當res.data沒值的時候undefined
this.myData=res.data
#當前值為undefined
console.log(this.myData.name)
#報以下錯誤
VM214:1 Uncaught TypeError: Cannot read properties of undefined (reading ‘name’)
at <anonymous>:1:11
1
2
3
4
5
6
7
解決辦法
使用可選鏈操作符 ?.
就以上問題進行修復(fù)
obj?.name
this.myData=res?.data
數(shù)組類型
數(shù)據(jù)沒有值時 數(shù)組[index] 數(shù)組下標獲取值會報錯 尤其是對鏈式結(jié)構(gòu)使用數(shù)組下標一層一層獲取數(shù)據(jù)
舉個例子: this.data[0].children[0].children[0].children[0]文章來源:http://www.zghlxwxcb.cn/news/detail-419906.html
在這種情況下 如果中間某一個數(shù)組沒有數(shù)據(jù)就會出現(xiàn)報錯
VM322:1 Uncaught TypeError: Cannot read properties of undefined (reading ‘[0]’)
at :1:7
————————————————
版權(quán)聲明:本文為CSDN博主「愛編程的梨清」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/nbsl_/article/details/127438683文章來源地址http://www.zghlxwxcb.cn/news/detail-419906.html
到了這里,關(guān)于解決 Cannot read properties of undefined類型的報錯的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!