PDA

View Full Version : Array Issue



thesprucegoose
03-12-2009, 07:47 PM
Ok this might be a bit complicated (or not) but...

I have data coming in from an external source that automatically assigns a number value to an action. I have to check to see if a variable equals that number then I have to change that variable to equal the text value.

This is the only way I can think to do it (but there has to be a better way...):



if (photoCaptionID0 == "24001"){
photoCaptionID0 = "Bat Ray Swimming"
}

//72 entries later...

if (photoCaptionID0 == "24073"){
photoCaptionID0 = "Blue Shark Swimming"
}

if (photoCaptionID1 == "24001"){
photoCaptionID1 = "Bat Ray Swimming"
}

//72 entries later...

if (photoCaptionID1 == "24073"){
photoCaptionID1 = "Blue Shark Swimming"
}

//Do this for photoCaptionID2-5

var photoCaptionIDZero = document.getElementById('photoCaptionID0');
if (photoCaptionIDZero)
photoCaptionIDOne.innerHTML = photoCaptionID0;

var photoCaptionIDOne = document.getElementById('photoCaptionID1');
if (photoCaptionIDOne)
photoCaptionIDOne.innerHTML = photoCaptionID1;

//Do this for 2-5



That would be about 400 lines of code. Is there a way to use arrays to achieve the same thing?

--thesprucegoose

jscheuer1
03-12-2009, 09:55 PM
You could make an array:


var swimmers = [
"Bat Ray Swimming",
"Something Else Swimming",
. . .
"Blue Shark Swimming" //no comma after the last entry
];

You should end up with 73 entries in the array. They will be known as swimmers[0] through swimmers[72]. Then you could do:


photoCaptionID0 = swimmers[photoCaptionID0 - 24001];
photoCaptionID1 = swimmers[photoCaptionID1 - 24001];
photoCaptionID2 = swimmers[photoCaptionID2 - 24001];
photoCaptionID3 = swimmers[photoCaptionID3 - 24001];
photoCaptionID4 = swimmers[photoCaptionID4 - 24001];
photoCaptionID5 = swimmers[photoCaptionID5 - 24001];