类型错误:'未定义'不是对象

TypeError: 'undefined' is not an object

本文关键字:对象 未定义 类型 错误      更新时间:2023-09-26

我有一个功能失调的Javascript程序,它一直给我带来问题。然而,它抛出了一个我不理解的错误:

TypeError: 'undefined' is not an object (evaluating 'sub.from.length')

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

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...

任何想法都很棒。坦率地说,我不明白为什么我会得到一个关于我已经明确检查了(typeof(sub.from))类型的东西的TypeError。。。

我不知道如何检查某个东西是否未定义,同时得到一个未定义的错误。你在用什么浏览器?

你可以用以下方式检查(额外=并使长度成为真实的评估)

if (typeof sub !== 'undefined' && sub.from && sub.from.length) {

[更新]

我看到你重置了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

我的猜测是,错误不在if语句上,而是在for(i...语句上。在Firebug中,你可以在出现错误时自动中断,我想它会在那一行中断(而不是在if语句上)。

如果您想为对象赋值,并且它以角度显示此错误,请尝试此操作。。

构造器中的板条箱对象

this.modelObj = new Model();//<----------------在上声明对象之后