问题描述
在节点v10中管理“未定义”时遇到一些问题
考虑以下对象:
const dictionary = {
weeklyContest: {
victorySubject: {
en: 'Congratulations,you are this week\'s lucky winner!',fr: 'Félicitations,vous êtes l\'heureux gagnant de cette semaine!',de: 'Herzlichen Glückwunsch,Sie sind der glückliche Gewinner dieser Woche!',es: '¡Felicidades,eres el afortunado ganador de esta semana!',ru: 'Поздравляем,вы счастливый обладатель этой недели!',default: 'Congratulations,you are this week\'s lucky winner!'
}
},default: {
victorySubject: {
en: 'Congratulations,you are today\'s lucky winner!',you are today\'s lucky winner!'
}
}
};
和以下代码:
let contestSlug = 'nonExistingContest';
let stringName = 'victorySubject';
let stringLocale = 'fr';
let contestProp = (typeof(dictionary[contestSlug]) === 'undefined' || typeof(dictionary[contestSlug][stringName]) === 'undefined') ? 'default' : contestSlug;
let localeProp = (typeof(dictionary[contestProp][stringName][stringLocale]) === 'undefined') ? 'default' : stringLocale;
contestProp
被正确分配了'default'
,因为没有名为'nonExistingContest'
的第一级属性,使第5行的第二个类型检查变为:
let localeProp = (typeof(dictionary['default']['victorySubject']['fr']) === 'undefined') ? 'default' : stringLocale;
现在,考虑到我连接了调试控制台,并考虑了此调试结果:
contestProp
> 'default'
stringName
> 'victorySubject'
stringLocale
> 'fr'
typeof(dictionary[contestProp][stringName][stringLocale]) === 'undefined'
> true
typeof(dictionary['default']['victorySubject']['fr']) === 'undefined'
> true
我不明白为什么第5行上的localeProp分配会返回错误:
Cannot read property 'victorySubject' of undefined
尽管我实际上只想检查未定义的内容。 我已经检查了类似的问题,并且它们都建议了替代的实现,但是我真的很想了解导致错误的行为。 有任何想法吗?预先感谢您的宝贵时间!
解决方法
我通过每次与需要比较的部分对象创建一个中间变量来解决该问题:
OLD
let contestProp = (typeof(dictionary[contestSlug]) === 'undefined' || typeof(dictionary[contestSlug][stringName]) === 'undefined') ? 'default' : contestSlug;
let localeProp = (typeof(contestStrings) === 'undefined' || typeof(contestStrings[stringLocale]) === 'undefined') ? 'default' : stringLocale;
新
let contestProp = (typeof(dictionary[contestSlug]) === 'undefined') ? 'default' : contestSlug;
let partialDictionary = dictionary[contestProp];
contestProp = (typeof(partialDictionary[stringName]) === 'undefined') ? 'default' : contestSlug;
partialDictionary = dictionary[contestProp][stringName];
let localeProp = (typeof(partialDictionary) === 'undefined' || typeof(partialDictionary[stringLocale]) === 'undefined') ? 'default' : stringLocale;
我仍然不遵循导致错误的逻辑。在接受这个答案之前,我会稍等一些想法。