为什么这个条件总是成立?

时间:2019-10-10 17:12:34

标签: javascript angular typescript

quiz.html

SELECT to_char(day, 'MMYY') as mmyy
FROM bi_core.fact_campaign_device_stats_daily
WHERE DAY = '2019-07-01'

firebase database is look like this

<ul *ngFor="let q of categoryid;"> <li colspan="4"> <strong>Q.No. {{q.questionId}}</strong> {{q.questionName}} </li> <li> <ul *ngFor="let o of q.options; let i = index" (click)="selectedIndex = (i+q.questionId)"> <div> <li [ngClass]="{correctAnswer: o.Ans && selectedIndex===(i + q.questionId), wrongAnswer: !o.Ans && selectedIndex===(i+q.questionId)}"> <strong>{{o.Ans}}</strong> {{o.optionName}} </li> </div> </ul> </li> </ul> 类始终为correctAnswer。为什么?

2 个答案:

答案 0 :(得分:0)

“假”字符串实际上被视为 true 布尔表达式,请参见https://developer.mozilla.org/en-US/docs/Glossary/Falsy

为了解决此问题,您必须为您的o对象提供布尔值({Ans:false}而不是{Ans:“ false”})或运行类似的检查:o.Ans === “真正”。您可能还考虑使用类型转换相等性检查,例如o.Ans == true,但我不推荐这种方法。

答案 1 :(得分:0)

您的班级名称应用单引号引起来,并将条件语句放在方括号中:

<li
   [ngClass]="{'correctAnswer': (o.Ans && selectedIndex === (i + q.questionId)),
               'wrongAnswer': (!o.Ans && selectedIndex === (i+q.questionId)})">
   <strong>{{o.Ans}}</strong>  {{o.optionName}}
</li>

或者您可以使用三元运算符?

<li
   [ngClass]="(o.Ans && selectedIndex === (i + q.questionId)) ? 'correctAnswer' : 'wrongAnswer'">
   <strong>{{o.Ans}}</strong>  
   {{o.optionName}}
</li>

此外,您可以在HTML中显示调试信息,并查看表达式的计算方式:

<p>(o.Ans && selectedIndex === (i + q.questionId)) is 
    {{ (o.Ans && selectedIndex === (i + q.questionId)) }}</p> 

<p>(!o.Ans && selectedIndex === (i+q.questionId)}) is 
    (!o.Ans && selectedIndex === (i+q.questionId)})</p>