[英]What do I do to output a random string in my javascript array every time the page reloads?
I would like to have a page that when you reload it generates a random question. 我想要一个页面,当您重新加载它时会生成一个随机问题。 Here is my code so far: 到目前为止,这是我的代码:
function questions() { var question = ["What's You name?", "What's your age?", "Do you like pizza?"]; var randomQuestion = truth[Math.floor(idea.length * Math.random())]; document.getElementById('outputQ').innerHTML = randomQuestion; }
What HTML do I need to add in order to allow it to generate a random question every time the page is reloaded. 我需要添加什么HTML,以便每次重新加载页面时生成一个随机问题。 I would like the output to be in a paragraph tag so I can add CSS classes. 我希望输出在段落标记中,以便添加CSS类。
(function questions() { var question = ["Whats You name?", "Whats your age?", "Do you like pizza?"]; var i = Math.floor(Math.random()*3); document.getElementById('outputQ').innerHTML = question[i]; })();
<p id='outputQ'></p>
<script type="text/javascript">
var getAQuestion = function () {
var questions = [
"What's You name?",
"What's your age?",
"Do you like pizza?"
];
return questions[Math.round(Math.random()*(questions.length-1))];
};
var question = getAQuestion(); console.log(question);
</script>
You get one random question, when you generate a number between 0 and 2 (in an array with three entries). 当您生成一个介于0和2之间的数字(在具有三个条目的数组中)时,您会得到一个随机问题。 A random integer number between 0 and n is generated by Math.floor(Math.random() * (n + 1));
Math.floor(Math.random() * (n + 1));
生成一个介于0和n之间的随机整数Math.floor(Math.random() * (n + 1));
So you need to calculate in your case 因此,您需要根据情况进行计算
var i = Math.floor(Math.random() * 3);
You get the random entry out of the array with 您可以使用以下方法从数组中获得随机条目
question[i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.