Reputation: 2783
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
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
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
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