Menu
How can I not get the same number while using Math.floor(Math.random()); ?
>@RaulRogojan#1606256
> **[color=#069] I don't understand your code...[/color] **
>@RaulRogojan#1606260
> **[color=#069]... but I am trying to learn how to do that myself[/color] **
``<i>
</i>(function( d ) { /* see link #1 */
'use strict'; /* see link #2 */
const colorBtn = d.querySelector( '.colorBtn' );
const body = d.querySelector( 'body' );
let test; /* declare a block scope local variable */
let random; /* declare a block scope local variable */
const colors = [ '#F5534F', '#F3B900', '#313A87', '#1C213F', '#D96704', '#BF4904', '#8C0303', '#0D0D0D', '#98A665' ];
colorBtn.addEventListener('click', () => {
num(); /* call the random number function */
if ( test === random ) { /* test for repeat of random number */
num();
}
body.style.backgroundColor = colors[ random ];
test = random; /* reset test value ready for the next button click */
}, false );
function num() { /* create a random number */
random = Math.floor( Math.random() * colors.length );
}
}( document ));<i>
</i>
``
``<i>
</i>(function( doc /* see bottom, this is the reference to document, abbreviated */ ) {
const
body = doc.body, /* document.body will do, no need to search */
colorBtn = body.querySelector ('.colorBtn'), /* let's start our search from the body as we now have it */
colors = [ '#F5534F', '#F3B900', '#313A87', '#1C213F', '#D96704', '#BF4904', '#8C0303', '#0D0D0D', '#98A665' ],
/* Make randomNum just a general random number function that returns a random value */
randomNum = function(num) {
return Math.floor( Math.random() * num );
};
let numColors = colors.length, /* Assigning length here, to save looking up the array's length property repeatedly */
newColor = randomNum(numColors),
lastColor;
colorBtn.addEventListener('click', function() {
/* Using a while loop, just in case the same random number comes up more than twice */
while ( lastColor === newColor ) {
newColor = randomNum(numColors);
}
body.style.backgroundColor = colors[ newColor ];
lastColor = newColor; /* store newColor for next time the button is clicked */
}, false );
}( document )) /* reference to document passed in from the global scope */<i>
</i>
``
0.1.9 — BETA 4.23