DNac
DNac

Reputation: 2783

Get random string from array list

I have the code as below, but can't get it work. It should return 1 value from the myArray, but it returns "undefined". What's the problem?

HTML

<div id="quote"></div>

JavaScript

var myArray = ['January', 'February', 'March'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

function showquote(){
    document.getElementById('quote').innerHTML = myArray[rand];
}
showquote();

JSFiddle can be found here.

Upvotes: 0

Views: 10568

Answers (4)

wilsont
wilsont

Reputation: 141

The problem is that rand' is already the value from the array (e.g. "January"), var rand = myArray[Math.floor(Math.random() * myArray.length)];

so you cannot get value from the array again using myArray['January'].

You should change your Js function as below

function showquote(){
    document.getElementById('quote').innerHTML = rand;
}

Or change your variable

var rand = Math.floor(Math.random() * myArray.length);

Upvotes: 3

Yaje
Yaje

Reputation: 2831

this fiddle works.

var myArray = ['January', 'February', 'March'];
var rand = Math.floor(Math.random() * myArray.length);

function showquote(){
    document.getElementById('quote').innerHTML = myArray[rand];
}
showquote();

the problem is with this line

var rand = myArray[Math.floor(Math.random() * myArray.length)]; // dereferenced myArray[] twice here 

Upvotes: 4

sukhi
sukhi

Reputation: 924

use this

var myArray = ['January', 'February', 'March'];

var rand = Math.floor(Math.random() * myArray.length);

function showquote(){

    document.getElementById('quote').innerHTML = myArray[rand];
}
showquote();

Upvotes: 2

Falydoor
Falydoor

Reputation: 462

var rand = Math.floor(Math.random() * myArray.length);

Upvotes: 2

Related Questions