Shaun
Shaun

Reputation: 21

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 expected

In Firefox,Chrome & Safari, "Object expected" shows as "undefined".

Does anyone have any idea why 0,0 -> 1,2 succeeds but everything else fails?

Shaun.

Upvotes: 2

Views: 496

Answers (2)

Shaun
Shaun

Reputation: 1

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.

Upvotes: 0

slaphappy
slaphappy

Reputation: 6999

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();
  ...

Upvotes: 5

Related Questions