【问题标题】:Looping through array object to check value match only works for first iteration, subsequent iterations failing循环遍历数组对象以检查值匹配仅适用于第一次迭代,后续迭代失败
【发布时间】:2021-01-25 22:18:50
【问题描述】:

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

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

这是我的调试输出:

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;
        }
    }   
}

【问题讨论】:

  • 嗨,这个问题很令人困惑。 this.answers是什么类型,是对象还是数组?在最上面的几行中,您说您正在遍历对象,但从函数来看,它似乎是一个数组。您能否为this.answers 提供一些示例输入以及实际输出和所需输出?调试输出似乎不是很有帮助。
  • 嗨@ShivamSingla,感谢您的回复。它是一个数组。我已经提供了数组声明的完整代码、添加项目和更新的代码。当用户回答一个问题(在这种情况下选择哪些陈述是真或假)时,特定的问题编号和他选择的答案的数组被推送到数组中。如果问题号存在,则更新答案数组,如果问题号不存在,则将新的问题号和答案数组对推送到数组中。我的问题是问题编号检查仅适用于索引 0 中的数据。

标签: arrays typescript for-loop object ionic4


【解决方案1】:

以下代码应该可以工作。您的代码的问题是,当它是索引 0 时,没有匹配项。所以if 条件为假,else if 为真。接下来else if 块中的代码执行并立即返回(这会中断循环,停止函数执行并返回false)。因此,对于提供的示例,循环只运行一次。实际上,对于 num 和 this.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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2016-08-11
    • 2021-08-20
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多