我正在尝试在JavaScript中进行计时,并给出20个随机生成的数学问题的数学测验。但是,当按下开始键并启动计时器而不是输出问题时,我将得到[object,Object]。所以我的问题是如何更改它,以便返回随机生成的问题?
这是我的下面的JS:
window.onload = function () {
var seconds = 00;
var tens = 00;
var appendTens = document.getElementById("tens");
var appendSeconds = document.getElementById("seconds");
var buttonStart = document.getElementById('button-start');
var Interval ;
buttonStart.onclick = function() {
function generateQuestions () {
let randNum1 = Math.floor(Math.random() * 100) + 1;
let randNum2 = Math.floor(Math.random() * 100) + 1;
var op = ["*", "+", "/", "-"][Math.floor(Math.random() * 4)];
return {number1: randNum1, operator: op, number2: randNum2};
}
var problemList = [];
while (problemList.length < 20) {
problemList.push(generateQuestions());
document.getElementById("questions").innerHTML = problemList[0];
}
clearInterval(Interval);
Interval = setInterval(startTimer, 10);
}
function startTimer () {
tens++;
if(tens < 9){
appendTens.innerHTML = "0" + tens;
}
if (tens > 9){
appendTens.innerHTML = tens;
}
if (tens > 99) {
console.log("seconds");
seconds++;
appendSeconds.innerHTML = "0" + seconds;
tens = 0;
appendTens.innerHTML = "0" + 0;
}
if (seconds > 9){
appendSeconds.innerHTML = seconds;
}
}
}
答案 0 :(得分:0)
您使用此行返回对象。
return {number1: randNum1, operator: op, number2: randNum2};
如果您要返回字符串作为问题,可以键入:
return randNum1.toString() + op + number2.toString();
这部分也应该固定:
while (problemList.length < 20) {
problemList.push(generateQuestions());
document.getElementById("questions").innerHTML = problemList[0];
}
您需要每次显示新问题。并非每次都一样。
for(let i = 0; i < 5; i++) {
problemList.push(generateQuestions());
document.getElementById("questions").innerHTML = problemList[i];
}
答案 1 :(得分:0)
在这里我为您提供了一个简单的例子
var questionsElement = document.querySelector("#questions");
function randInt(max) {
return Math.floor(Math.random() * max);
}
function randQuestions(len) {
var questions = [];
while(questions.length < len) {
questions.push({number1: randInt(100), operator: ["+","*","-","/"][randInt(4)], number2: randInt(100)});
}
return questions;
}
var problemList = randQuestions(20);
for(var i = 0;i < problemList.length; i++) {
questionsElement.innerHTML += `<li>${problemList[i].number1} ${problemList[i].operator} ${problemList[i].number2} = ?</li>`;
}
ul {
padding: 0;
margin: 0;
list-style-type: none;
}
li {
background-color: lightgreen;
color: white;
padding: 10px;
margin-top: 5px;
font: bold 20px monospace;
}
<ul id="questions"></ul>