根据百分比查找任意长度数组中的项目

Fin*_*nnn 2 javascript

我有一系列的图像

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
Run Code Online (Sandbox Code Playgroud)

以上是可怕的代码.

我想要一种方法,允许奖品图像数组改变大小,并避免键入每个if语句.

我希望这是有道理的,我有一种感觉它没有.

jfr*_*d00 9

如果我理解你的要求,你想要一个百分比(从0到100)并找出你的数组中哪个图像最接近该百分比位置并获得该图像URL.如果是这样,你可以通过将百分比除以100来将其转换为十进制百分比,乘以数组的长度,然后将其舍入为整数.这将获得最接近您的百分比的数组索引.然后,您可以从数组中索引以获取所需的值.

你可以这样做:

function findPercentLocation(array, percent) {
    return(array[Math.round((percent / 100) * (array.length - 1))]);
}

var prizeImageArray = ['image1.png','image2.png','image3.png','image4.png'] 
var imageSrc = findPercentLocation(priceImageArray, 27);
Run Code Online (Sandbox Code Playgroud)

如果你想让它更强大,你可以保护0-100范围之外的百分比值,这样可以避免超出数组的范围:

function findPercentLocation(array, percent) {
    if (percent < 0) percent = 0;
    if (percent > 100) percent = 100;
    return(array[Math.round((percent / 100) * (array.length - 1))]);
}
Run Code Online (Sandbox Code Playgroud)