admin管理员组

文章数量:1287245

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.

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.

Share Improve this question asked Jul 4, 2014 at 8:20 DNacDNac 2,7838 gold badges33 silver badges56 bronze badges 6
  • 2 So, rand is already equal to month name. document.getElementById('quote').innerHTML = rand; – Andy Jones Commented Jul 4, 2014 at 8:22
  • First try some basic debugging: console.log(rand) – JJJ Commented Jul 4, 2014 at 8:23
  • and although this is simple error... have an upvote for clearly written question with a fiddle too – Andy Jones Commented Jul 4, 2014 at 8:25
  • Thank you all for the feedback. – DNac 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. – Alnitak Commented Jul 4, 2014 at 8:27
 |  Show 1 more ment

4 Answers 4

Reset to default 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 

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

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

use this

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

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

function showquote(){

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

本文标签: javascriptGet random string from array listStack Overflow