Forum Moderators: open

Message Too Old, No Replies

Preload Images from Multidimentional array

         

redwax

11:49 am on Dec 3, 2009 (gmt 0)

10+ Year Member



Hi

I'm not really very up on javascript, however, I have needed to create a multidimensional array of images which looks like this:

ar MultiArray = new Array(5)
MultiArray [1] = new Array(2)
MultiArray [1][1] = "gender-male.png"
MultiArray [1][2] = "gender-female.png"
MultiArray [2] = new Array(2)
MultiArray [2][1] = "hands-right.png"
MultiArray [2][2] = "hands-left.png"
MultiArray [3] = new Array(5)
MultiArray [3][1] = "height-1.png"
MultiArray [3][2] = "height-2.png"
MultiArray [3][3] = "height-3.png"
MultiArray [3][4] = "height-4.png"
MultiArray [3][5] = "height-5.png"

It works fine except for preloading. I have looked at scripts for preloading one dimensional arrays and have used what I thought was logical to create:

for (i=0; i < MultiArray.length; i++) {
for (j=0; j < MultiArray[i].length; j++) {
var preload = new Image();
preload.src = MultiArray[i][j];
}
}

which doesn't work!

Any thoughts?

Fotiman

2:09 pm on Dec 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to WebmasterWorld! It looks like when you are creating your array, your indexes begin at 1 instead of 0. Try this: replace all of that code above the "for" loops with this:

var MultiArray = [
["gender-male.png", "gender-female.png"],
["hands-right.png", "hands-left.png"],
["height-1.png", "height-2.png", "height-3.png", "height-4.png", "height-5.png"]
];

That will create the arrays to be indexed starting at 0, and is a much more compact method.

Note, in general you should not use "new Array", but instead define the array as a literal using [].

redwax

3:31 pm on Dec 3, 2009 (gmt 0)

10+ Year Member



Fotiman! You're a star. Thanks ever so much it works a charm. And that is a much better, neater way of assigning values to an array.

As it goes, I needed to start the indexes from 1 because the page output is generated from php and the images all start with an index of '1' so reflecting this in the javascript made live much easier. I have just assigned nothing the first array entry:

["", "height-2.png", "height-3.png", "height-4.png", "height-5.png"]

As a point of interest, perhaps I could have started my "for" loop as i=1? Would that have worked?

Fotiman

3:55 pm on Dec 3, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm not sure I understand what you mean by "the images all start with an index of '1'". It shouldn't matter what your PHP code does. Could you clarify what you mean? Is it that your PHP code loops from 1 to 5 and outputs
'height-' . n . '.png'
where n is the number, but height-1.png doesn't actually exist?