在Javascript中进行比较时如何避免分配? [英] How to avoid assignments while comparing in Javascript?
本文介绍了在Javascript中进行比较时如何避免分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将变量与值进行比较,并意外地使用'='代替了'==',因此代码看起来像这样:
I was trying to compare a variable to a value and accidently ended up using '=' in place of '==' hence the code looked like:
var test = 1;
if(test = 2) {
console.log(test);
}
代替:
var test = 1;
if(test == 2) {
console.log(test);
}
我假设已将值成功分配给变量,因此条件返回true,并执行了 console.log()
.我的假设正确吗?除了 Yoda条件参考
I assume the value was successfully assigned to the variable , hence the condition returned truthy and console.log()
was executed. Is my assumption correct? What is a good coding practice to avoid such mistakes besides Yoda Condition reference
推荐答案
Lint it. There are tools that can automatically analyze your Javascript and catch common errors like this.
这篇关于在Javascript中进行比较时如何避免分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文