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
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.