【发布时间】:2018-01-02 07:57:23
【问题描述】:
在下面的代码中包含一个非常简单的问题游戏(正在进行中)。到目前为止,我已经能够通过 onLoad 函数“qDisplayLoad()”显示“规则”消息。接下来,只要有人点击,onClick 函数“qDisplayClick”就会运行,从而从数组 (qArray) 中随机抽取。
我的问题: 一旦显示了从数组中选择的问题,您如何删除(拼接)它?我的目标是不要让同一个问题重复两次。在下面的代码中,您会发现我对“拼接”的业余尝试(并且它有点工作),但是数组推出了“未定义”。
var qLoad = 0;
var qArray = [
"Question 1",
"Question 2",
"Question 3",
"Question 4",
"Question 5"
];
var randomElement;
/* The text "Rules" appears when the page loads */
function qDisplayLoad() {
if (qLoad == 0) {
randomElement = "Rules";
qLoad = 1; /* Changes qLoad to "1" from "0" so the array begins within the "qDisplayClick" function */
}
document.getElementById("questions").innerHTML = randomElement;
}
/* A new question is pulled from the array everytime the mouse is clicked (up to a maximum of 5) */
function qDisplayClick() {
var randomNumber = Math.floor(Math.random() * qArray.length); /* Questions are randomly chosen and rounded down from the array */
if (qLoad += 1 && !(qLoad == 7)) {
qArray.splice(qArray,1);
randomElement = qArray[randomNumber];
} else if (qLoad == 0) {
randomElement = "Rules";
}
if (qLoad == 7) { /* After the 5th question, text will appear for the pop up */
randomElement = "WIP - POP UP PLACEHOLDER";
}
document.getElementById("questions").innerHTML = randomElement;
}
【问题讨论】:
-
我发现了这个有用的教程,但是对于我的代码来说,如果仍然显示“未定义”。 w3schools.com/js/tryit.asp?filename=tryjs_array_remove
-
你的意思是数组推出未定义的?
标签: javascript arrays undefined splice