【问题标题】:Disabling cannot read property of undefined禁用无法读取未定义的属性
【发布时间】:2020-12-04 09:29:52
【问题描述】:

我知道我的 gfg[item[0] + 1][item[1]] 不存在,但我需要进一步运行我的代码:

 arrayfirstword.forEach(item => {
                if(typeof(gfg[item[0] + 1][item[1]]) !== undefined){
                    console.log(1);
                }

有没有办法消除这个错误?

【问题讨论】:

    标签: javascript arrays error-handling


    【解决方案1】:

    没有。您必须调整您的代码并确保您不会从未定义的值访问内容:

    arrayfirstword.forEach(item => {
    
                    if(item && gfg && item[0] && item[1] && gfg[item[0] + 1] && typeof(gfg[item[0] + 1][item[1]]) !== undefined){
                        console.log(1);
                    }
    

    要避免重复的表达式:

    arrayfirstword.forEach(item => {
                    if (!item || !item[0] || !item[1] || !gfg) return;
                    let key = item[0] + 1;
                    let val = gfg[key];
                    if (val && val[item[1]]) {
                        console.log(1);
                    }
                    
    

    在这种情况下,它更丑陋,但如果条件变得更复杂,最好将其拆分为 5-6 行,而不是有一个巨大的嵌套复杂条件。

    【讨论】:

    • 谢谢老兄,但我没明白,你还在检查未定义变量的值吗?
    • @s662720h_uu ||&& 是懒惰的。当他们可以返回值时,他们停止评估条件。例如,true || someFunc()不会运行 someFunc(),因为 true || anything === true。与false && someFunc() 相同,将不会运行someFunc(),因为false && anything === falseundefined.attribute 是一个错误,因此您可以通过执行 if (v && v.attribute) 来避免它,如果 v 未定义 v && v.attribute 仅检查 v 因为 undefined 是“假的”并且它不会尝试从 @ 获取 attribute 987654338@
    猜你喜欢
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2020-10-30
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多