JS?解決Cannot?set?properties?of?undefined的問題
TypeError: Cannot set properties of undefined
類型錯誤:無法設(shè)置未定義的屬性
問題解析
當前的是當前對象或者數(shù)組是undefined,但是卻用來引用屬性或者索引
比如下面兩種情況
const value = undefined value.a // TypeError: Cannot read properties of undefined (reading 'a') value[0] // TypeError: Cannot read properties of undefined (reading '0')
或者是當前的value值不是我們顯式聲明的undefined,而是運算之后得到undefined,之后我們再去用它
const value = {}
value.a.b // TypeError: Cannot read properties of undefined (reading 'b')
value.a // undefined解決方案
問題清楚了, 解決的方式就是不用undefined直接去應(yīng)用對象,解決報錯問題可以用以下方法
const value = undefined
//解決方法1: if條件
if(value){
value = {}
value.a
}
// 解決方法2:?運算符
value?.a
// 解決方法3:||運算符
const preValue = value || {}
preValue.a到此這篇關(guān)于JS 如何解決Cannot set properties of undefined的文章就介紹到這了,更多相關(guān)js解決 Cannot set properties of undefined內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript 異步調(diào)用框架 (Part 1 - 問題 & 場景)
在Ajax應(yīng)用中,調(diào)用XMLHttpRequest是很常見的情況。特別是以客戶端為中心的Ajax應(yīng)用,各種需要從服務(wù)器端獲取數(shù)據(jù)的操作都通過XHR異步調(diào)用完成。2009-08-08
javascript打印大全(打印頁面設(shè)置/打印預(yù)覽代碼)
打印頁面設(shè)置,打印頁面預(yù)覽在打印過程中經(jīng)常會遇到,網(wǎng)上搜集整理了一些實用的打印方法與大家分享,感興趣的朋友可以了解下哈2013-03-03

