【问题标题】:While using typeof, getting "Cannot read property '0' of null"使用 typeof 时,出现“无法读取属性 '0' of null”
【发布时间】:2015-06-22 14:13:54
【问题描述】:

我想要什么

我正在尝试使用 typeof 来检查数组元素是否存在。原因是为了防止Cannot read property '0' of null 错误。但是,只是尝试检查元素是否存在会导致错误。

我的尝试

if (typeof foo[0] !== 'undefined') 
{ 
    // I want to get here
}

if (typeof(foo[0]) !== 'undefined') 
{ 
    // I want to get here
}

这是循环的一部分,前四次迭代有效,第五次假定无效,第六次假定有效。但是,它在第​​五个循环中失败了。我不能写异常,因为输入可以改变循环的哪些迭代应该工作,哪些不应该工作。

我相信这是正确的方法,我不应该根据这些 stackoverflow 答案收到这种行为。

Check if an array item is set in JS

Checking if a key exists in a JavaScript object?

JavaScript isset() equivalent

How to check if a multidimensional array item is set in JS?

我认为关键在于 typeof 是您可以在尝试使用元素之前检查是否设置了元素并给自己抛出错误。其他用户似乎可以使用完成此操作。我猜我正在做一些不同的事情。如何检查是否设置了数组索引而不使脚本失败,因为我正在查看未设置的数组索引。

更多上下文中的代码

应该不是必需的,只是装箱。

            for (templ_i=0; templ_i<number_of_fields; templ_i++)
            {
                // Font size
                if (d['font_size_group'][templ_i]['font_size'])
                {
                    size_re = new RegExp('"text_' + line + '" font-size="\\d+(\\.[0-9]+)?"', 'g');
                    current_line = svg_template.match(size_re);
                    size_re = new RegExp('[^_"]\\d+(\\.[0-9]+)?', 'g');
                    if (typeof current_line[0] !== 'undefined') { current_font_size = current_line[0].match(size_re); }
                    console.log(current_font_size);
                }
            }

【问题讨论】:

  • 您了解短路语句的工作原理吗?你的 foo 是 undefined/null 所以它没有索引的孩子。你最好把 if 语句短路到if (foo &amp;&amp; foo[0]) 不需要“typeof” foo[0] 测试它是否为空/未定义,如果不是返回 true 如果它是 null 返回 false ...除非 foo [ 0] 是一个布尔值,那么是的,您可能需要特别检查它是否不等于 undefined/null

标签: javascript jquery arrays


【解决方案1】:

typeof foo[0] 这样做:

  • 评估foo[0]
  • 返回一个带有其类型名称的字符串

但是,如果foo 为空,foo[0] 将抛出。

所以你可以使用

foo != null                  /* Filter out undefined and null */
&&
typeof foo[0] != 'undefined' /* Check the type of the property */

【讨论】:

  • 我确定 foo 在这种情况下不为空,但无论如何我都会应用此修复程序以查看它是否有效。
  • 我参考了你的答案。 :D
  • 哇,没关系,这行得通。但是我仍然确定 foo 不为空。如果 foo 不为 null 并且是冗余检查,为什么这会阻止 foo[0] 抛出错误?
  • 我会将其标记为正确,但是,我仍然不明白它如何解决问题,因为我正在检查并且在中断循环中, foo 无论如何都不为空。如果你有时间并且有能力,请解释一下。
  • 如果你想保存击键,数组计算为true,所以你可以写foo &amp;&amp; typeof foo[0]...。请注意,在某些情况下,这比检查 == null 稍微宽松一些。
【解决方案2】:
if (typeof(foo && foo[0]) !== 'undefined') 
{ 
   // I want to get here
}

【讨论】:

    【解决方案3】:

    typeof 返回“字符串”。

    如果你想使用 typeof - 请正确使用:

    if (typeof foo[something] != 'undefined') 
    {
        // Now you can get foo[something]
    }
    

    重要

    a = null;
    typeof a
    

    将返回“对象”

    【讨论】:

    • 实际上,这就是我发布问题时所拥有的。现在我已经恢复了它,因为我意识到这不是导致问题的原因。
    • 是的,更新太晚了 ;) 但是 javascript 很奇怪 {} + {} = NaN, [] + [] = "" 和 {} + [] = 0 所以记住这个 xD
    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 2016-12-11
    • 2017-10-29
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2017-03-04
    • 2021-12-02
    相关资源
    最近更新 更多