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
4 Answers
Reset to default 4this 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
版权声明:本文标题:javascript - Get random string from array list - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741270384a2369175.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论