所以我试图在javascript中制作一个猜谜游戏类型的东西。我想要它,以便我可以在不更改其他代码的情况下不断添加新的人和问题,它将正常工作。现在这就是我到目前为止所看到的,它似乎应该有效,但它的表现非常难以预测和奇怪。有人可以看看我的代码,看看我哪里出错了?
这里:
// ORDER: Name, Age, Gender, Glasses
var peopleremaining = [
["Evan",17,"male",false],
["Liam",10,"male",false],
["Logan",15,"female",false],
["Brynn",7,"female",false],
["Caz",37,"male",true]
];
var questions = [
["Is the person you're thinking of older than 16?",1,16],
["Is the person you're thinking of male?",2,"male"],
["Is the person you're thinking of older than 10?",1,10],
["Does the person you're thinking of wear eyeglasses?",3,true]
];
var randomquestion;
var randomquestionnumber;
function newquestion() {
randomquestionnumber = [Math.floor((Math.random()*questions.length))];
randomquestion = questions[randomquestionnumber];
document.getElementById("mainheading").innerHTML = randomquestion[0];
}
function buttonpressed(option) {
var questionsubject = randomquestion[1];
var questionvalue = randomquestion[2];
var peopleremaininglength = peopleremaining.length;
if (option == "yes") {
if (questionsubject == 1) {
for (var t=0;t<peopleremaininglength;t++) {
if (peopleremaining[t][questionsubject] < questionvalue) {
peopleremaining.splice(t, 1)
}
}
}
else {
for (var t=0;t<peopleremaininglength;t++) {
if (peopleremaining[t][questionsubject] != questionvalue) {
peopleremaining.splice(t, 1)
}
}
}
}
else {
if (questionsubject == 1) {
for (var t=0;t<peopleremaininglength;t++) {
if (peopleremaining[t][questionsubject] >= questionvalue) {
peopleremaining.splice(t, 1)
}
}
}
else {
for (var t=0;t<peopleremaininglength;t++) {
if (peopleremaining[t][questionsubject] == questionvalue) {
peopleremaining.splice(t, 1)
}
}
}
}
questions.splice(randomquestionnumber, 1);
if (peopleremaining.length == 1) {
alert("You are thinking of " + peopleremaining[0][0]);
}
else {
newquestion();
}
}
答案 0 :(得分:1)
问题是你正在迭代“peopleremaining”数组的每个元素,但是在那个循环中你正在修改数组。
快速解决这个问题的方法就是像这样摆脱循环:
for (var t = 0; t < peopleremaininglength; t++) {
if (peopleremaining[t][questionsubject] < questionvalue) {
peopleremaining.splice(t, 1)
t = peopleremaininglength; // Add this line to break out of the loop
}
}
答案 1 :(得分:0)
你犯了典型错误 - 你在迭代中修改了迭代对象。