Javascript Get Random result with probability for specific array

前端 未结 3 970
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 07:15

i have a array and i need to do it randomly show the output by probability below are my code

var shirts = [
                      [\"images/fantastic-logo.pn         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 07:26

    For a short array this should be enough, using getRandomInt from Mozilla Developers:

    function getRandomInt(max) {
        return Math.floor(Math.random() * Math.floor(max));
    }
    
    var shirts = [
        ["images/fantastic-logo.png", "12.65"],
        ["images/fantastic-word.png", "10.00"],
        ["images/free-product.png", "15.50"]
    ];
    
    var random = getRandomInt(100);
    var selectedShirt;
    if (random <= 50) {
        selectedShirt = shirts[0];
    } else if (random > 50 && random < 75) {
        selectedShirt = shirts[1];
    } else {
        selectedShirt = shirts[2];
    }
    
    $("#image").html($("").attr("src", shirts[selectedShirt][0]));
    $(".price").html("$" + shirts[selectedShirt][1]);
    

    Note that you can use less numbers like in Ray's answer. For a bigger array you may use a better approach.

提交回复
热议问题