2

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.

2 Answers 2

5
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();
  ...
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.