-2

I used Math.random() to generate a random number between 1 and however many items are in the array availableNumbers()

However, when the document's innerHTML is updated with this, suggestedNumber resolved to undefined,

I tried subtracting 1 from randomNumber but that did not make a difference.

I have checked the W3 documentation and it looks like this is implemented correctly...

How would one best go about retrieving a random item from an array? Is there a better implementation than what I sought to implement?

var availableNumbers = ["0", "911"];
function numberSuggestion() {
    var randomNumber = Math.random() * availableNumbers.length -1;
    var suggestedNumber = availableNumbers[randomNumber];
    document.getElementById("suggestion").innerHTML = "How about dialing " + suggestedNumber + "? Don't like this number? Click the button above again!";
}
InterLinked
  • 1,247
  • 2
  • 18
  • 50

2 Answers2

0

Multiplying Math.random() by an integer will produce a floating point value in the range [0, number). You need to remove the fractional portion to get the integer portion:

var randomNumber = Math.floor(Math.random() * availableNumbers.length);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thanks, but this didn't solve the problem. I figured since it would resolve to a whole number, OOO wouldn't have mattered. – InterLinked May 18 '17 at 02:50
  • Without the -1, this works perfectly! (So I guess I didn't need to subtract 1 after all!) – InterLinked May 18 '17 at 02:51
  • 2
    Might be cool if the explanation covered the key point about needing an integer result. (I know the code shown does this, but given that the explanation talks about something else the `Math.floor()` part seems less important.) – nnnnnn May 18 '17 at 02:56
  • @nnnnnn I've fixed the explanation now. – JLRishe May 18 '17 at 14:06
-1

Yo try this function:

Array.prototype.choice = function(){
    return this[~~(Math.random()*this.length)];
};

// now you can call it like this :)
console.log( ["0", "911"].choice() );
nick
  • 1,197
  • 11
  • 16
  • 2
    What was wrong with the original code, and why does this fix it? (I know the code you've shown does work, but an explanation would be helpful for beginners.) – nnnnnn May 18 '17 at 02:52
  • Its better, reusable, faster, more readable, everything – nick May 18 '17 at 02:53
  • 4
    Modifying the built-in prototypes is definitely not "reusable", "readable" or "everything". Also `~~` - don't be tricky, there are built-in functions for rounding, that are explicit. – zerkms May 18 '17 at 02:53