0

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.

6
  • 2
    So, rand is already equal to month name. document.getElementById('quote').innerHTML = rand; Commented Jul 4, 2014 at 8:22
  • First try some basic debugging: console.log(rand) Commented Jul 4, 2014 at 8:23
  • and although this is simple error... have an upvote for clearly written question with a fiddle too Commented Jul 4, 2014 at 8:25
  • Thank you all for the feedback. Commented Jul 4, 2014 at 8:26
  • @AndyJones I've submitted a close vote on the basis that the error is so simple and the answers unlikely to help anyone else in future. Commented Jul 4, 2014 at 8:27

4 Answers 4

4

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 
Sign up to request clarification or add additional context in comments.

1 Comment

@ejay_francisco the error is not a syntax error. It's merely a case of the OP accidentally trying to dereference myArray[] twice - once in the rand call and again in showquote().
3

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);

1 Comment

@DNac this is the clearest answer here, the only one to correctly explain the double indexing into the array. IMHO you should accept this one.
2

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

Comments

2

use this

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

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

function showquote(){

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.