-2

所以我试图用javascript做一个猜谜游戏类型的东西。我想要它,这样我就可以在不更改其他代码的情况下继续添加新的人和问题,它会工作得很好。现在这就是我到目前为止所得到的,看起来它应该可以工作,但它的行为非常不可预测和奇怪。有人可以看看我的代码,看看我哪里出错了吗?

JSFiddle 演示

这里:

// 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();
}

 }
4

2 回答 2

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
            }
        }
于 2013-11-11T08:11:25.347 回答
0

你犯了典型的错误——你在迭代中修改了迭代对象。

于 2013-11-11T08:10:41.840 回答