-4

var myName = ['Beth', 'Chris', 'Carl', 'April', 'Cinnamon','Ethan'];

I want to be able to pick a number or name from an array and use that same value again? I am using javascript

  • Please provide your attempted code and describe what your challenge is with it so we can assist you in resolving that. – Mark Schultheiss Apr 02 '17 at 12:37
  • var randomVal = myName[Math.floor(Math.random() * myName.length) - 1 ]; –  Apr 02 '17 at 12:49
  • 1
    Possible duplicate of [Getting a random value from a JavaScript array](http://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array) – Phillip Hartin Apr 02 '17 at 21:53

2 Answers2

0

You can use random Math function. If your array has 6 elements. you can use the below JavaScript.

myName[Math.floor(Math.random()*6)]
Karpak
  • 1,927
  • 1
  • 15
  • 16
0

Why would something simple such as this not work. Up to your to explore the truly "random" aspect of this but likely OK for most things. Note that arrays are 0 based thus the 0,myName.length-1 parameters.

function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
var myName = ['Beth', 'Chris', 'Carl', 'April', 'Cinnamon','Ethan'];
var randomName = myName[randomIntFromInterval(0,myName.length-1)];
console.log(randomName);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100