我在一个测试应用程序中有一个对象,它存储问题编号和用户答案。我有一个函数,它循环遍历对象,以检查对象中是否存在问题编号。如果是,则更新用户答案,如果不是,则生成新条目。
我的问题是,对于我可以添加的第一个条目,检查问题编号是否存在并更新用户答案,但对于所有其他条目,它与问题编号不匹配,因此所有更新都显示为对象中的新条目。
这是我的调试输出:
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
块中的代码执行并立即返回(这会中断循环,停止函数执行并返回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
,否则当没有匹配时。