检查未定义时无法读取未定义的 属性

Cannot read property of undefined while checking for undefined

我在 Node v10

中管理 'undefined' 时遇到了一些问题

考虑以下对象:

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!',
            default: 'Congratulations, 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 的赋值 returns 错误:

Cannot read property 'victorySubject' of undefined

尽管我实际上只是想检查未定义。 我已经检查了类似的问题,它们都建议了替代实现,但我真的很想了解导致错误的行为。 有任何想法吗?提前感谢您的宝贵时间!

我通过每次使用我需要比较的部分对象创建一个中间变量来解决这个问题:

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;

我仍然不遵循导致错误的逻辑。在接受这个答案之前,我会等待一些想法。