我需要在从对象池中挑选问题后删除或标记属性问题[i] null
var pool = {
question1: {
question: "This is question number 1",
options: ["Option 1", "Option 2", "Option 3", "Option 4"],
answer: 0,
used: false /*I add this to mark if this question is used but it doesn't work*/
},
question2: {
question: "This is question number 2",
options: ["Option 1", "Option 2", "Option 3", "Option 4"],
answer: 1,
used: false
},
question3: {
question: "This is question number 3",
options: ["Option 1", "Option 2", "Option 3", "Option 4"],
answer: 2,
used: false
},
...
};
逻辑:从池中随机挑选一个问题。然后问题被删除或设置为空,因此用户不会再次看到相同的问题(除非重置游戏)。
我已尝试使用delete object.property
,但它不起作用:问题仍然存在并生成。另外,我选择了一个属性:used = false
(上面)并设置used = true
,然后使用if语句对其进行过滤,但它仍然无法正常工作。
function randomQuest(obj) {
var keys = Object.keys(obj);
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
function nextQuest() {
currentQuest = randomQuest(pool);
$(".question").html(currentQuest.question);
for (var i = 0; i < 4; i++) {
$(".options").append("<div class='option'>" + currentQuest.options[i] + "</div>");
}
$(".option").on("click", checkAnswer);
//TO DO: filter used question
// I've added the code below here but they don't work
}
尝试1:delete pool.currentQuest;
尝试2:
if (!currentQuest.used) {
$(".question").html(currentQuest.question);
}
else {
currentQuest = randomQuest(pool);
}
答案 0 :(得分:1)
由于delete pool.currentQuest
没有名为pool
的属性,因此currentQuest
无效。它具有question1
到question3
的属性。
您需要跟踪您检索的问题属性,然后将其删除(即delete pool[myVarThatContainsTheQuestPropertyName]
)。
就我个人而言,我个人会有一系列问题:
var pool = [{id: 1, question: "", answers: []}, {...}]
然后您可以通过pool = pool.filter(function(q) { return q.id !== currentQuest.id })