gpt4 book ai didi

javascript - JS : How to return 'undefined' instead of throwing error 'cannot read property x of undefined'

转载 作者:行者123 更新时间:2023-12-02 11:51:29 25 4
gpt4 key购买 nike

当父属性不存在时,让 js 返回 undefined 而不是抛出错误的最佳方法是什么?

示例

a = {}
b = a.x.y.z
// Error: Cannot read property 'value' of undefined
// Target result: b = undefined

最佳答案

您必须检查每个属性是否存在:

var b;
if (a.x && a.x.y && a.x.y.z) {
b = a.x.y.z
}

或者,类似于另一张海报的“safeGet”功能:

var get = function (obj, ns) {
var y = ns.split('.');
for(var i = 0; i < y.length; i += 1) {
if (obj[y[i]]) {
obj = obj[y[i]];
} else {
return;
}
}
return obj;
};

用途:

var b = get(a, 'x.y.z');

关于javascript - JS : How to return 'undefined' instead of throwing error 'cannot read property x of undefined' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10936491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com