3

For example

var names = array["bob","tom","jake"];

how could I select a random name from that array and assign it to the variable

var randomName = I don't know what goes here
0

2 Answers 2

3

You should use Math.random method.

var random=Math.floor((Math.random() * names.length));
var randomName=names[random];

Also, in javascript the arrays are declared like this :

var names = ["bob","tom","jake"];

not

var names = array["bob","tom","jake"];

var names = ["bob","tom","jake"];
var random=  Math.floor((Math.random() * names.length));
var randomName=names[random];
console.log(randomName);

Sign up to request clarification or add additional context in comments.

9 Comments

How does var random work?
@TheLegend27 It generates a random number between 0 and names.length - 1.
As @BenM said, it generates a random number from 0 and names.length-1
Why do you have to subtract 1?
Because array indexes are from 0.
|
0

Use random method

 var randomName = names[Math.floor(Math.random()*items.length)];

Comments