Problem populating 2d Image Array in Javascript
I have a need for a 2d image array in Javascript and have wrote the following: -
var arrImages = new Array(3,3);
var strTemp;
for (intX=0; intX<3; intX++)
{
for (intY=0;intY<3;intY++)
{
strTemp = "<br>arrImages[" + intX + "][" + intY + "]";
try
{
arrImages[intX][intY] = new Image();
document.write(strTemp + " - Success");
}
catch (err)
{
document.write(strTemp + " - Fail - " + err.description);
}
}
}
This produces the following in IE: -
arrImages[0][0] - Success
arrImages[0][1] - Success arrImages[0][2] - Success arrImages[1][0] - Success arrImages[1][1] - Success arrImages[1][2] - Success arrImages[2][0] - Fail - Object expected arrImages[2][1] - Fail - Object expected arrImages[2][2] - Fail - Object expectedIn Firefox,Chrome & Safari, "Object开发者_开发百科 expected" shows as "undefined".
Does anyone have any idea why 0,0 -> 1,2 succeeds but everything else fails?
Shaun.
var arrImages = new Array(3,3);
is equivalent to
var arrImages = [3, 3];
(Documentation on MDN here)
So arrImages[2]
is undefined where indexes 0 and 1 actually contains objects. Note that javascript arrays are not fixed-size, so you don't need to specify a length when creating them.
You need to create multidimensional arrays manually, for example :
arrImages = new Array();
for (intX=0; intX<3; intX++)
{
arrImages[intX] = new Array();
...
Now re-written as:-
var arrImages = new Array();
var strTemp;
for (intX=0; intX<3; intX++)
{
arrImages[intX] = new Array();
for (intY=0;intY<3;intY++)
{
strTemp = "<br>arrImages[" + intX + "][" + intY + "]";
try
{
arrImages[intX][intY] = new Image();
document.write(strTemp + " - Success");
}
catch (err)
{
document.write(strTemp + " - Fail - " + err.description);
}
}
}
Thanks, works perfectly.
精彩评论