I have an array of images
var prizeImage;
//this is a dynamic amount
var result = 55;
//the length of this array will change. Images will be added/removed
var prizeImageArray = ['image1.png','image2.png','image3.png','image4.png']
//I want to avoid having to type each of these if statements.
if(result < 25){
prizeImage = prizeImageArray[0];
}
if(result > 26 && result < 50){
prizeImage = prizeImageArray[1];
}
if (result...)//and so on
The above is terrible code.
I want a method that will allow for the prize image array to change size and to avoid typing each of the if statements.
I hope this makes sense, I have a feeling it doesn’t.
If I understand what you’re asking, you want to have a percent (from 0-100) and find out which image in your array is closest to that percent location and get that image URL. If so, you can do that by dividing the percent by 100 to turn it into a decimal percentage, multiplying by the length of the array and then rounding that to an integer. That gets you the array index that is closest to your percentage. You can then index from the array to fetch the desired value.
You can do it like this:
If you want to make it more robust, you could protect against percent values outside the 0-100 range like this which would avoid extending beyond the bounds of your array: