Javascript代码表现出意想不到的逻辑行为

时间:2013-04-05 16:09:42

标签: javascript html5

我的程序正在回应展示意外行为。

selectQuestion()的预期行为:

随机选择一个问题类别并检查所需的难度级别。 搜索问题列表,将最近未播放的标准添加到潜在问题列表中。如果没有满足此随机选择标准的问题,请重复上述步骤,直到找到问题为止。

selectQuestion()的实际行为:

selectQuestion()会选择recentQuestions[]中的问题,而不是随意选择新类别。

其他信息:

dda[]是一个对象数组,每个对象都有categorydifficulty

question[]是一个对象数组,每个对象都有questionanswers[]correctAnswercategorydifficulty

recentQuestions[]是一个整数数组。 (每个整数是question[]

中问题的索引
function selectQuestion()
{
    //Create an array we can use to store the numbers of any questions which meet our criteria
    var potentialQuestions = new Array();
    // While there are no questions which meet our criteria, pick new critieria
    // (This prevents the program from getting 'stuck' if criteria can't be met)
    while(potentialQuestions.length == 0) {
        // Select a category at random, retrieve the difficulty we're looking for
        var randomSelection = Math.floor(Math.random()*dda.length);
        var category = dda[randomSelection].category; 
        var difficulty = Math.floor(dda[randomSelection].difficulty+0.5);
        // For each question we have (in question[]) 
        for(q = 0; q < question.length; q++) {
                    // If the category and the difficulty meet our criteria
            if(question[q].category == category & question[q].difficulty == difficulty) {
                            // Check if the question has been played recently
                            // by looping through recentQuestions[] 
                var playedRecently = false; 
                for(r = recentQuestions.length; r=0; r++) {
                    if(recentQuestions[r] == q) {
                        playedRecently = true; 
                    }
                }
                // If the question has not been played recently 
                if(!playedRecently) {
                                    // Add it to potentialQuestions[]
                    potentialQuestions.push(q); 
                }
            }
        }
    }

    // Select a question at random from our potential questions 
    var selectedQuestion = potentialQuestions[Math.floor(Math.random()*potentialQuestions.length)]; 

    // If 5 recent questions have been stored, remove the oldest 
    if (recentQuestions.length == 5) {
        recentQuestions.shift(); 
    }

    // Add the selected level to recentQuestions[]
    recentQuestions.push(selectedQuestion); 
    return selectedQuestion; 
}

我不确定这种行为来自哪里。任何想法都会受到欢迎!谢谢!

解决了!

for (r= recentQuestions.length; r=0; r++)实际上应该是for (r=0; r<recentQuestions; r++) - 绝对是那些日子之一!尔加!谢谢大家:)

2 个答案:

答案 0 :(得分:2)

第二个答案就像第一个答案。您在for循环条件中有一个赋值而不是比较。 (=代替==)。

看起来你打算倒数?那么,你的增量应该是r--吗?

答案 1 :(得分:0)

在你的if语句中,你有一个&;你可能想要&&&是一个按位,而不是逻辑和。