我正在創(chuàng)建一個(gè)定時(shí)瑣事游戲,它從數(shù)組中隨機(jī)選擇一個(gè)存儲(chǔ)在對(duì)象中的問題。目前,我讓程序從數(shù)組中隨機(jī)選擇一個(gè)問題,但它有時(shí)會(huì)選擇一個(gè)已經(jīng)被選擇的問題。我希望我的 currentQuestion 變量只是數(shù)組中的一個(gè)對(duì)象questionChosen: false我嘗試了一個(gè) while 循環(huán),但我認(rèn)為我沒有正確格式化它導(dǎo)致程序無限循環(huán)從而無法工作。 // This is how objects are stored in the questionsArr var q1 = { title: "Question 1", a1: "answer 1.", a2: "answer 2.", a3: "answer 3.", a4: "answer 4.", questionChosen: false, };這是我的函數(shù),它生成一個(gè)新問題并設(shè)置它們是否已被選擇為真 function newQuestion() { time = 30; var currentQuestion = questionsArr[Math.floor(Math.random() * questionsArr.length)]; if (intervalId && intervalId >= 0) { clearInterval(intervalId); } if (!clockRunning) { clockRunning = true; } currentQuestion.questionChosen = true; intervalId = setInterval(countdown, 1000); console.log(intervalId); console.log(clockRunning); $("#question-box").text(currentQuestion.title); $("#a1").text(currentQuestion.a1); $("#a2").text(currentQuestion.a2); $("#a3").text(currentQuestion.a3); $("#a4").text(currentQuestion.a4); }
如何從數(shù)組中隨機(jī)選擇具有特定屬性值的對(duì)象
森林海
2021-11-18 21:09:08