Thank you! As a total newbie developer this actually helped me complete my first (extremely simple and crude) website. Now to understand the Math command… :)
Thank you for an example!
But I need to say there’s a missing subtraction “- 1”, because in case when our randomizer returns the maximum value “1”, we get myArray[3] — a non-existent element in the array. So we need to substract 1 from the array length in order to stay in the arrays existing indexes boundaries.
var randomItem = myArray[Math.floor(Math.random()*(myArray.length – 1))];
This is super succicnt, and here I was doing this all the time like a total schmo…
…
JS Result
EDIT ON
function randomNum(minVal, maxVal) {
do {
r = Math.random();
} while (r == 1);
return minVal+Math.floor(r*(maxVal+1-minVal));
}
var coolwords = new Array();
coolwords[0] = “robot”;
coolwords[1] = “inferno”;
coolwords[2] = “giga”;
coolwords[3] = “infinity”;
coolwords[4] = “pow”;
coolwords[5] = “smash”;
coolwords[6] = “boom”;
coolwords[7] = “crunch”;
coolwords[8] = “robot”;
coolwords[9] = “inferno”;
document.body.innerHTML = coolwords[randomNum(0, coolwords.length-1)];
Hi guys this is best example I was searching the same. It was difficult to find out value randomly now it becomes very easy. Thanks for sharing.
Thanks you very much
Great post guys
var mrrandom = Math.floor(Math.random()*10);
$(“.myclass”).eq(mrrandom).click();
This is Best example. you can try it.
Thank you! As a total newbie developer this actually helped me complete my first (extremely simple and crude) website. Now to understand the Math command… :)
Thank you for an example!
But I need to say there’s a missing subtraction “- 1”, because in case when our randomizer returns the maximum value “1”, we get myArray[3] — a non-existent element in the array. So we need to substract 1 from the array length in order to stay in the arrays existing indexes boundaries.
var randomItem = myArray[Math.floor(Math.random()*(myArray.length – 1))];