【发布时间】: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