TypeError:'undefined'不是对象

use*_*482 10 javascript

我有一个目前相当功能失调的Javascript程序,这一直导致我的问题.但是,它抛出一个我不明白的错误:

TypeError: 'undefined' is not an object (evaluating 'sub.from.length')
Run Code Online (Sandbox Code Playgroud)

正如你可能猜到的那样,我正在尝试做的是检查dict length中的某个" from"数组sub.这是整个函数源代码,这里是我认为导致错误的循环代码:

console.log(afcHelper_ffuSubmissions.length); // just for debugging, returns the correct number
for (var i = 0; i < afcHelper_ffuSubmissions.length; i++) { // this whole section works fine
    var sub = afcHelper_ffuSubmissions[i];
    //console.log("THIS IS BROKEN DOWN BY LINK",afcHelper_Submissions[i]);
    if (pagetext.indexOf(afcHelper_ffuSections[sub.section]) == -1) {
        // Someone has modified the section in the mean time. Skip.
        document.getElementById('afcHelper_status').innerHTML += '<li>Skipping ' + sub.title + ': Cannot find section. Perhaps it was modified in the mean time?</li>';
        continue;
    }
    var text = afcHelper_ffuSections[sub.section];
    var startindex = pagetext.indexOf(afcHelper_ffuSections[sub.section]);
    var endindex = startindex + text.length;

    console.log(sub); 
    if (typeof(sub.from) != 'undefined' && sub.from.length > 0) { // ** problem spot?? this is the code i recently added.
        for (var i = 0; i < sub.from.length; i++) {
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // and then it goes on from here...
Run Code Online (Sandbox Code Playgroud)

任何想法都会很棒.坦率地说,我只是看不出为什么我得到的TypeError东西我已经明确检查了(typeof(sub.from))的类型......

HMR*_*HMR 6

我不确定你怎么能检查某些东西是否未定义,同时得到一个未定义的错误.你使用的是什么浏览器?

您可以通过以下方式检查(额外=并使长度成为真正的评估)

if (typeof(sub.from) !== 'undefined' && sub.from.length) {
Run Code Online (Sandbox Code Playgroud)

[更新]

我看到你重置sub并从而重置sub.from但是没有重新检查sub.from是否存在:

for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
            mainid = sub.from[i]['id'];
            var sub = afcHelper_Submissions[mainid]; // <== re setting sub
Run Code Online (Sandbox Code Playgroud)

我的猜测是错误不在if语句上,而是在for(i...语句中.在Firebug中,您可以自动中断错误,我猜它会在该行上中断(而不是在if语句中).

  • 此外,非常糟糕的做法来触摸您正在迭代的阵列. (3认同)