0

I am having an issue in which i am trying to select a random number using an arrays length as the parameter.

var myArray = [1,2,3,4,5];
var r = Math.floor(Math.random(myArray.length));

That is what i have so far, if my array is size 7 for example i would like r to be a random number up to 7.

So far it return r as 0, even when testing in the browser console

Any help would be greatly appreciated!

GrandeurH
  • 147
  • 1
  • 1
  • 13

1 Answers1

0

The Math.random() function does not pay attention to parameters; it always returns a random value in [0, 1). Thus to get a random integer between 0 and some upper limit, you'd use

var r = Math.floor(Math.random() * myArray.length);
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • @NickDewitt note that the indexes of a JavaScript array run from 0 up to `length - 1`. – Pointy Nov 28 '17 at 14:00
  • But `Math.random()` never returns 1. (That's what the notation `[0, 1)` means.) – Pointy Nov 28 '17 at 14:00
  • Hi, thanks for the suggestions guys, still having a bit of trouble with that, i tried in the console and it only returns 1 for some reason? – GrandeurH Nov 28 '17 at 14:07
  • @GrandeurH well it's hard to say because you posted very little of your code. The `Math.random()` function definitely returns values between 0 and 1, and multiplication works fine in JavaScript. – Pointy Nov 28 '17 at 14:11
  • I added in the array in which i am using if that helps – GrandeurH Nov 28 '17 at 14:16
  • @GrandeurH if you use the code in this answer (*not* your posted code), the value of `r` will range from 0 through 4, which is correct because your array has 5 elements. – Pointy Nov 28 '17 at 14:18
  • Apologies it does work , thanks for the answer! – GrandeurH Nov 28 '17 at 14:20
  • 1
    @NickDewitt: If `.length === 5`, `Math.random() * 5` will be `[0, 5)`. Flooring that will give you a random value out of `[0, 1, 2, 3, 4]`. – Cerbrus Nov 28 '17 at 14:21