类型错误:“undefined”不是对象
2013-07-18
188214
我有一个目前相当不正常的 Javascript 程序,它给我带来了很多问题。但是,它抛出了一个我无法理解的错误:
TypeError: 'undefined' is not an object (evaluating 'sub.from.length')
正如您可能猜到的那样,我正在尝试做的是检查
sub
字典中某个“
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
...
2个回答
我不确定您如何才能只检查某个东西是否未定义,同时又收到未定义的错误。您使用的是什么浏览器?
您可以按照以下方式检查(extra = 并使 length 成为真值评估)
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 语句上)。
HMR
2013-07-18
如果您想为对象分配值并且它在 angular 中显示此错误,请尝试一下此方法..
在构造函数中创建对象
this.modelObj = new Model();
//<---------- 在上述声明对象之后
Cani vasa
2020-08-28