?>>>>>>問題
"cannot read property of undefined" 是一個常見的 JavaScript 錯誤,包含我在內(nèi)很多人都會遇到,表示你試圖訪問一個未定義(undefined)對象的屬性。這通常是因?yàn)槟阍谠L問一個不存在的對象或者變量。為了解決這個問題,你需要檢查你的代碼,確保在訪問對象屬性之前,對象已經(jīng)被正確定義。
How can I avoid 'cannot read property of undefined' errors?
如何避免“無法讀取未定義的屬性”錯誤?
Given that below object , not all object has same property , normally happens in JSON format , 如果閣下遇到以下問題,a中未必包含b,b中未必包含c,甚至a也不一定存在,應(yīng)該如何優(yōu)雅的判斷呢。
// Where this array is hundreds of entries long, with a mix
// of the two examples given
var test = [{'a':{'b':{'c':"foo"}}}, {'a': "bar"}];
for (i=0; i<test.length; i++) {
// OK, on i==0, but 'cannot read property of undefined' on i==1
console.log(a.b.c);
}
>>>>>>解決方法
強(qiáng)力推薦!封裝GetProperty方法,從對象中獲取屬性,屬性不存在則返回默認(rèn)值
This is a common issue when working with deep or complex JSON object, so I try to avoid try/catch or embedding multiple checks which would make the code unreadable. I usually use this little piece of code in all my projects to do the job.?
/* Example: getProperty(myObj, 'aze.xyz', 0) // return myObj.aze.xyz safely
* accepts array for property names:
* getProperty(myObj, ['aze', 'xyz'], {value: null})
*/
function getProperty(obj, props, defaultValue) {
var res, isvoid = function(x) {return typeof x === "undefined" || x === null;}
if(!isvoid(obj)) {
if(isvoid(props))
props = [];
if(typeof props === "string")
props = props.trim().split(".");
if(props.constructor === Array) {
res = props.length>1 ? getProperty(obj[props.shift()], props, defaultValue) : obj[props[0]];
}
}
return typeof res === "undefined" ? defaultValue: res;
}
思路二,我的項(xiàng)目中用的就是這個方法 !!! 好用
//by zhengkai.blog.csdn.net
const temp = {};
console.log(getSafe(()=>a.b.c, '0'));
function getSafe(fn, defaultVal) {
try {
if (fn() === undefined || fn() === null) {
return defaultVal
} else {
return fn();
}
} catch (e) {
return defaultVal;
}
}
使用默認(rèn)參數(shù)值
在函數(shù)定義時,為參數(shù)設(shè)置默認(rèn)值,以確保即使沒有傳遞參數(shù),也不會出現(xiàn)未定義的屬性。
function example(param = "default value") {
console.log(param);
}
example(); // 輸出 "default value"
hasOwnProperty檢查屬性是否存在
const obj = {
key: "value"
};
if (obj.hasOwnProperty("key")) {
console.log(obj.key);
} else {
console.log("Key does not exist");
}
?
使用邏輯或操作符(||)
const obj = {
key: "value"
};
console.log(obj.key || "Default value"); // 輸出 "value"
使用解構(gòu)賦值
const obj = {
key: "value"
};
const { key = "Default value" } = obj;
console.log(key); // 輸出 "value"
可選鏈操作符optional chaining語法(.?)
- If you use JavaScript according to ECMAScript 2020 or later, see?optional chaining.
- TypeScript has added support for optional chaining in version?3.7.
// use it like this
obj?.a?.lot?.of?.properties
使用可選鏈操作符(?.):可選鏈操作符允許你在嘗試訪問對象的屬性時提供一個后備值,以防屬性不存在。?
const obj = {
key: "value"
};
console.log(obj?.key ?? "Default value"); // 輸出 "value"
不是很建議的try/catch
A quick workaround is using a try/catch helper function with ES6?arrow function:?文章來源:http://www.zghlxwxcb.cn/news/detail-845583.html
function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
// use it like this
console.log(getSafe(() => obj.a.lot.of.properties));
// or add an optional default value
console.log(getSafe(() => obj.a.lot.of.properties, 'nothing'));
?不夠優(yōu)雅的“多重判斷”方法
ry this. If?a.b
?is?undefined
, it will leave the?if
?statement without any exception.文章來源地址http://www.zghlxwxcb.cn/news/detail-845583.html
if (a && a.b && a.b.c) {
console.log(a.b.c);
}
到了這里,關(guān)于Javascript/Node.JS中如何用多種方式避免屬性為空(cannot read property of undefined ERROR)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!