[英]Error while accessing javascript array element inspite of having checks
I am doing following in my javascript code 我正在用我的javascript代码执行以下操作
if(
typeof player['stats'] != undefined &&
typeof player['stats']['guild'] != undefined &&
typeof player['stats']['guild']['master'] != undefined &&
typeof player['stats']['guild']['master']['since'] != undefined
)
However I get error: 但是我得到错误:
Cannot read property 'since' of null
I have been stuck with this for a while. 我已经坚持了一段时间。 Can any javascript gurus help me please? 任何JavaScript大师都可以帮我吗?
typeof returns string, so compare against "undefined" typeof返回字符串,因此与“ undefined”进行比较
if(
typeof player['stats'] != "undefined" &&
typeof player['stats']['guild'] != "undefined" &&
typeof player['stats']['guild']['master'] != "undefined" &&
player['stats']['guild']['master'] != null &&
typeof player['stats']['guild']['master']['since'] != "undefined"
)
Just check if the value is truthy: 只需检查该值是否为真:
if(
player['stats'] &&
player['stats']['guild'] &&
player['stats']['guild']['master'] &&
player['stats']['guild']['master']['since'] != undefined // only check the last one as it is probably not an object but another value such as 0 (depending on what your data looks like, if you have it as an object then just remove the != undefined check)
)
You could write a fairly simple object getter function which you pass the object and then a dot-delimited key to find a value like so: 您可以编写一个相当简单的对象获取器函数,该函数先传递对象,然后使用点分隔键查找值,如下所示:
function getObj(obj, key) {
return key.split(".").reduce((acc, cur) => {
if (acc !== undefined) {
return acc[cur];
}
return acc;
}, obj);
}
Then, you can grab the value that you want and see if it's undefined or not: 然后,您可以获取所需的值,并查看其是否未定义:
const player = {
stats: {
guild: {
master: {
since: '2004'
}
}
}
};
const since = getObj(player, 'stats.guild.master.since');
if (since) {
// do some code
}
This is a handy utility function you can use on any object and makes your if statement much prettier. 这是一个方便的实用函数,可以在任何对象上使用,并使if语句更漂亮。
You can also avoid the multiple lookups with a temporary variable: 您还可以避免使用临时变量进行多次查找:
player = { stats: { guild: { master: null } } } if ((temp = player.stats) && (temp = temp.guild) && (temp = temp.master) && (temp = temp.since) !== undefined) console.log(true , temp) else console.log(false, temp) player.stats.guild.master = { since: 'today' } if ((temp = player.stats) && (temp = temp.guild) && (temp = temp.master) && (temp = temp.since) !== undefined) console.log(true , temp) else console.log(false, temp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.