[英]Uncaught TypeError : Cannot read property 'length' of undefined
I am facing the Uncaught TypeError : Cannot read property 'length' of undefined in the output console while running the following code using JavaScript:我面临未捕获的类型错误:在使用 JavaScript 运行以下代码时,无法在输出控制台中读取未定义的属性“长度” :
var field = [];
function setup()
{
createCanvas(625, 625);
field = generateField();
}
function draw()
{
background(51);
for(var i=0; i<field.length; i++)
{
field[i].draw();
}
}
function generateField()
{
var f = [];
for (var i = 0; i < 625; i++)
{
f.push(new Tile(i%25, Math.floor(i/25), "BARRIER"));
}
}
The error is coming in the line: for(var i=0; i < field.length; i++)错误出现在行中: for(var i=0; i < field.length; i++)
Any suggestions on how to debug this problem will be appreciated.任何有关如何调试此问题的建议将不胜感激。
You are most probably just missing a return statement in this function:您很可能只是在此函数中缺少一个 return 语句:
function generateField()
{
var f = [];
for (var i = 0; i < 625; i++)
{
f.push(new Tile(i%25, Math.floor(i/25), "BARRIER"));
}
return f; // <-- this line
}
You are missing a return
statement on the generateField
function and as it is explained on Functions - JavaScript|MDN :您在
generateField
函数上缺少return
语句,正如在Functions - JavaScript|MDN 中所解释的那样:
A
function
without areturn
statement will return a default value.没有
return
语句的function
将返回一个默认值。 In the case of aconstructor
called with thenew
keyword, thedefault
value is the value of itsthis
parameter.对于使用
new
关键字调用的constructor
,default
值是其this
参数的值。 For all other functions, the defaultreturn
value isundefined
.对于所有其他函数,默认
return
值是undefined
。
In this case, generateField
is being used as a regular function and it will returns undefined
.在这种情况下,
generateField
被用作常规函数,它将返回undefined
。 Because of this, an Uncaught TypeError
is thrown when trying to access a length
property on the field
variable.因此,当尝试访问
field
变量的length
属性时,会抛出Uncaught TypeError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.