-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」配列の各要素を繰り返し処理していることですが、そのループ内で配列を変更していることです。

これを回避する簡単な方法の 1 つは、次のようにループから抜け出すことです。

        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 に答える