0

i was coding for a small project but my random array picker doesnt work

var btnarray = [xfn.left, xn.left, xnln.left, xln.left, xnn.left];

(this is the array)

var rand = btnarray[Math.floor(Math.random() * 4)];

(this is the random picker var)

Well, when i start, the rand value results equal to btnarray[0]

anyone can help me please?

Oh i perfectly know that the variables are all different.

Thanks

Diasky VB
  • 45
  • 1
  • 8
  • 1
    what do you mean by it doesn't work? – Junius L Dec 07 '19 at 20:11
  • the code works as expected the only thing ou need to change is to use the array length in your random ```btnarray[Math.floor(Math.random() * btnarray.length)];``` – Junius L Dec 07 '19 at 20:14
  • Does this answer your question? [Getting a random value from a JavaScript array](https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) – Junius L Dec 07 '19 at 20:16
  • Instead of posting 2 lines from your code, put it in a bit of context: are these lines both in a function, one right after the other? – trincot Dec 07 '19 at 20:18
  • the rand var is equal every time to xfn.left. – Diasky VB Dec 07 '19 at 20:27

3 Answers3

0

Since your array's length is 5, you need to multiply the value of the random function by that number. Better yet, use the length property.

var rand = btnarray[Math.floor(Math.random() * btnarray.length)];
Rob
  • 491
  • 4
  • 14
0

You shouldn't use Math.floor since it will make very hard to get the last element in your btnarray array, you'll need to get exactly the number btnarray.length in order to get at that element. Also, floor tends to flatten probability outcomes and looks like you're stuck on some value(s) since it's threshold is forcing you to have the greatest integer smaller than or equal to some number.

You should use round instead, this will even the probability for every array element and will give you more apparently random indexes. Try this, it's already tested with a dummy btnarray array variable and works fine.

var rand = btnarray[Math.round(Math.random() * btnarray.length)];
Javier Silva Ortíz
  • 2,864
  • 1
  • 12
  • 21
0

if you toss this in the head tag of your html document:

<script src="https://randojs.com/1.0.0.js"></script>

you can just do this:

var randomValue = rando(btnarray).value

I usually go with randojs.com because it can handle pretty much any random functionality you need, and it's all short and easy to read.

Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15