/    Sign up×
Community /Pin to ProfileBookmark

Getting the same index with Math.random

How can I not get the same number while using Math.floor(Math.random()); ?
https://codepen.io/raul-rogojan/pen/KjLpww?editors=0110

to post a comment
JavaScript

13 Comments(s)

Copy linkTweet thisAlerts:
@cootheadJul 14.2019 — Hi there RaulRogojan,

does this help...

https://codepen.io/anon/pen/NZVwWR

_coothead_
Copy linkTweet thisAlerts:
@codyhillauthorJul 14.2019 — @coothead#1606255 Hi, Nope.

I don't understand your code...
Copy linkTweet thisAlerts:
@cootheadJul 14.2019 — > @RaulRogojan#1606256

> **[color=#069] I don't understand your code...[/color]**


It solves your problem, does it not, regardless of your lack of comprehension. 😀

_coothead_
Copy linkTweet thisAlerts:
@codyhillauthorJul 14.2019 — @coothead#1606257 It did, but I am trying to learn how to do that myself :)
Copy linkTweet thisAlerts:
@cootheadJul 14.2019 — > @RaulRogojan#1606260

> **[color=#069]... but I am trying to learn how to do that myself[/color]**


Well, instead of petulantly writing "**Nope**" , why didn't

you, instead, request explanations for those parts of the

code which were testing your comprehension?

_coothead_
Copy linkTweet thisAlerts:
@codyhillauthorJul 14.2019 — @coothead#1606261 I did do that in the original post. Your response was a code that had the same effect as what I wanted, not an explanation of how I can improve my code towards the effect I needed.
Copy linkTweet thisAlerts:
@cootheadJul 14.2019 — Hi there RaulRogojan,

here are all the comments - [color=#069] /* information */ [/color] - for the code amendments...

``<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', () =&gt; {
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>
``

  • 1. [url=https://developer.mozilla.org/en-US/docs/Glossary/IIFE]**[color=#069]Immediately Invoked Function Expression[/color]**[/url]

  • 2. [url=https://humanwhocodes.com/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/]**[color=#069]It’s time to start using JavaScript strict mode[/color]**[/url]


  • _coothead_
    Copy linkTweet thisAlerts:
    @codyhillauthorJul 15.2019 — @coothead#1606263 Thanks you
    Copy linkTweet thisAlerts:
    @cootheadJul 15.2019 — No problem, you're very welcome. 😁

    _coothead_
    Copy linkTweet thisAlerts:
    @rpg2009Jul 19.2019 — Each to their own, but my take

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

    Personally I think this is a bad example to be introducing IIFE's and discussions on scope and 'Use strict'. To a novice if that is what Raul is, it's just going to be confusing.

    If he is struggling with random numbers, I think it would be best to go back to basics, and get an understanding of variable types, primitives, references — learn about functions, invocation, lexical scope, variable hoisting and so on.

    What I see here, is Raul asking 'How do I ride a bike?', and the response is 'Watch me do wheelies and tricks, does that help?'
    Copy linkTweet thisAlerts:
    @codyhillauthorJul 19.2019 — @rpg2009#1606465 Much better :D

    2 questions tho.

    From where did you got lastColor, how did u define it?

    And why did you put ,false after the eventListener ?
    Copy linkTweet thisAlerts:
    @rpg2009Jul 19.2019 — lastColor is defined under newColor. When I say defined, added is probably a better description as I don't assign a value to it. It's value is 'undefined'

    It is not until the event fires for the first time and newColor's value is assigned to it, that it gets a value. This means on the first firing of the event the while loop's condition lastColor === newColor will equal false.

    As far as the setting of false on addEventlistener, I have to admit my DOM knowledge is pretty rusty — it's a habitual default setting.

    A bit of a refresh is needed, but to give you a very rough idea, it is there to set whether the capture phase of the Event object is set. The capturing phase is when the event object trickles down from the parent to child nodes and picks up on fired events.

    The other stage is known as bubbling, and this where the event bubbles up from the child node to it's parents.

    You can try out this [(https://codepen.io/anon/pen/eqmqYd)] and experiment with changing the parent element's addEventListener capture setting to true or false. Also try adding or removing the stopPropagation on the child element. It's gives us some clues as to what is going on.

    A more detailed explanations.

    [(https://www.w3.org/TR/DOM-Level-3-Events/#event-flow)

    and

    [https://www.quirksmode.org/js/events_order.html#link4]

    A few pointers for what it's worth. When stuck try isolating the problem code and keep it simple. console.log and console.dir can come in very handy when debugging. Obviously it's beneficial to read up and experiment.

    Cheers
    Copy linkTweet thisAlerts:
    @codyhillauthorJul 20.2019 — @rpg2009#1606517 Cool, thx! I'll make some more research.
    ×

    Success!

    Help @codyhill spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.23,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...