遍历数组对象以检查值匹配仅适用于第一次迭代,后续迭代失败

Looping through array object to check value match only works for first iteration, subsequent iterations failing

我在测验应用程序中有一个对象,用于存储问题编号和用户答案。我有一个循环遍历对象的函数,以检查对象中是否存在问题编号。如果是,则更新用户答案,如果不是,则创建新条目。

我的问题是对于我可以添加的第一个条目,检查问题编号是否存在并更新用户答案,但对于所有其他条目,它与问题编号不匹配,因此所有更新都显示为对象中的新条目。

这是我的调试输出:

0: {questionNo: 0, answer: Array(2)}
1: {questionNo: 2, answer: Array(2)}
2: {questionNo: 2, answer: Array(2)}

问题编号 (questionNo) 中应该只有一个条目 2,因为函数应该检查问题编号是否已经存在并且更新数组。该功能仅适用于索引 0 中的数据,所有其他问题编号均不匹配并成为新条目。

函数是:

public answers: any  = [];

public count = 0;


constructor(){

}

addItem(item, item2){
this.answers.push({
    questionNo: item,
    answer: item2
});
}

checkIfQnAnswered(num){
    
    for(let i = 0; i < this.answers.length; i++) 
    {
        //console.log(i);
        if(this.answers[i].questionNo == num)
        {
             console.log("Question number exists at " + i);
            //this.count++;
            //return this.count;
            return true;
        }
        else if(this.answers[i].questionNo != num)
        {
            console.log("Question number does not exisit");
            //this.count++;
            //return this.count;                
            return false;
        }
    }
    

}

updateQnAnswered(item, item2){
    for(let i = 0; i < this.answers.length; i++) 
    {
        if(this.answers[i].questionNo == item)
        {
           // this.count++;
            //this.answers.splice(i, 1);
            this.answers[i].questionNo = item;
            this.answers[i].answer = item2;
        }
    }   
}

以下代码应该可以工作。您的代码的问题在于,当索引为 0 时,没有匹配项。所以 if 条件为假,而 else if 变为真。接下来 else if 块中的代码执行并立即 returns (这打破了循环,停止函数执行和 returns false)。因此,对于提供的示例,循环 运行s 仅一次。实际上,对于 numthis.answers 的任何值,循环只会 运行 一次,因为 if-else 阶梯是详尽无遗的,并且都包含 return 语句.

checkIfQnAnswered(num) {
    for(let i = 0; i < this.answers.length; i++) {
        if(this.answers[i].questionNo === num) {
            // found first match, now return true
            console.log("Question number exists at " + i);
            //this.count++;
            //return this.count;
            return true;
        }
    }

    // we are here, means no match was found
    return false
}

在上面的代码中,函数return true 当循环找到第一个匹配时; false否则当没有匹配时。