迭代一个字符串数组:TypeError:无法读取属性' 0'未定义的

时间:2018-01-28 15:23:36

标签: javascript arrays string

我有一个不同长度的字符串数组,我想迭代所有数组以检查LongestCommonPrefix(一个简单的&leetcode.com问题)。 我发现很难避免错误(在本Q的标题中给出),但(据我所知)它似乎不一致。为了探讨这些问题,我试过这个:

    l = ["str","string"];
    longest = l[1].length;
    // some 2nd level string elements do not exist in the array
    for (i = 0; i < longest; i++) {
        console.log('typeof: ', i, typeof  l[0][i]);
    }

    // the 3rd array element has not been defined / initialised
    for (i = 0; i < l[0].length + 1; i++) {
        console.log('typeof: ', i, typeof  l[3][i]);
    }

得到这个结果:

    typeof:  0 string
    typeof:  1 string
    typeof:  2 string
    typeof:  3 undefined
    typeof:  4 undefined
    typeof:  5 undefined
    /Volumes/some_path/testarray.js:11
        console.log('typeof: ', i, typeof  l[3][i]);
                                               ^

    TypeError: Cannot read property '0' of undefined
        at Object.<anonymous> 

    (/Volumes/some_path/testarray.js:11:44)
    ...

为什么第一遍遍历数组并返回&#39; undefined&#39;,然而第二遍(故意尝试迭代未定义的元素[3])失败。 如何在没有运行时错误的情况下成功处理该错误?

1 个答案:

答案 0 :(得分:0)

如果您尝试访问对象的不存在的属性¹,您将得到未定义 但是,如果您尝试访问null或undefined属性,则会出现类型错误。

l[3]未定义,因此尝试访问属性0会给您一个错误,但是,l [0]既不是未定义的也不是null,因此您可以尝试访问所需的任何属性,这将返回值如果存在或未定义,如果它不存在(或确实存在但设置为未定义)。

¹同样适用于原语,因为它们将被提升为对象以访问属性。