![](/img/trans.png)
[英]I have some instances of a class and I pushed them into an array. Can I loop through the array and update the price of all the array objects?
[英]How to loop through instances of an Object that are pushed into an array?
我的目標是制作一款通過隨機生成向用戶詢問3個問題的游戲。 我通過創建一個類並創建新的問題實例並將其推入數組來解決這個問題。 之后,我做了一個函數,可以“提示”數組中的每個問題,並要求用戶輸入正確的答案。 如果用戶輸入的答案不正確,則會給用戶1更多機會正確猜測答案,否則用戶會松懈。
在這段代碼中,我將3個問題推入問題數組,並編寫了一行代碼“ const randomVal = Math.floor(Math.random()* questions.length);”。 生成數組的隨機元素。
我的目標是隨機打印插入數組中的所有3個問題,但是我的代碼僅打印1個隨機問題,然后中斷。
我試過在Questionz函數中使用for循環,但是我的循環沒有提示3個不同的問題,而是提示了3次相同的問題。
// Creating a class
class Quiz
{
constructor(ti,opA,opB,opC,ans) // Easy
{
this.title = ti;
this.optionA = opA;
this.optionB = opB;
this.optionC = opC;
this.answer = ans;
}
}
// Making an array that will hold all the questions and options
const questions = [];
questions.push(new Quiz("Who is the greatest laker of all time?","Kobe",
"Shaq", "Magic", "Kobe"));
questions.push(new Quiz("Who is the greatest hockey player of all
time?","Crosby", "Ovechkin", "Kessel", "Crosby"));
questions.push(new Quiz("What is Torontos Baseball team called?","Blue
Jays", "Rex Sox", "Yankees", "Blue Jays"));
const randomVal = Math.floor(Math.random() * questions.length);
let que1; // This is global
let i=0;
function Questionz() // Easy Questions (lvl 1)
{
que1 = prompt(`Q. ${questions[randomVal].title}
\n\n1.${questions[randomVal].optionA}
\n2.${questions[randomVal].optionB}\n3.${questions[randomVal].optionC}`);
Validation(randomVal);
}
// BOTTOM FUNCTION GIVES PROMPTED VALUE VALIDATION
function Validation(randomVal)
{
while(que1 !== questions[randomVal].answer)
{
que1 = prompt(`${que1} is Incorrect!\n\nPlease try again!`);
i++;
if(que1 === questions[randomVal].answer)
{
alert("Correct!\n\nPress OK to move onto the next question!");
}
else if(i===1)
{
alert(`${que1} is incorrect.\n\nYou have lost.`);
break;
}
}
}
Questionz();
您將要在循環中每次生成一次隨機數,而不是頁面加載一次。 此函數循環3次並創建3個隨機數。
function Questionz() // Easy Questions (lvl 1)
{
for(let z = 0; z < questions.length; z++) {
let randomVal = Math.floor(Math.random() * questions.length);
que1 = prompt(`Q. ${questions[randomVal].title}
\n\n1.${questions[randomVal].optionA}
\n2.${questions[randomVal].optionB}\n3.${questions[randomVal].optionC}`);
Validation(randomVal);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.