I am facing the Uncaught TypeError : Cannot read property 'length' of undefined in the output console while running the following code using 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++)
Any suggestions on how to debug this problem will be appreciated.
You are most probably just missing a return statement in this function:
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 :
A
function
without areturn
statement will return a default value. In the case of aconstructor
called with thenew
keyword, thedefault
value is the value of itsthis
parameter. For all other functions, the defaultreturn
value isundefined
.
In this case, generateField
is being used as a regular function and it will returns undefined
. Because of this, an Uncaught TypeError
is thrown when trying to access a length
property on the field
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.