在条件陈述中分配变量,良好实践与否? [英] Assign variable in if condition statement, good practice or not?
问题描述
一年前,我将经典的OO语言(如Java)转移到JavaScript。 Java中绝对不推荐使用以下代码(甚至不正确):
I moved one years ago from classic OO languages such like Java to JavaScript. The following code is definitely not recommended (or even not correct) in Java:
if(dayNumber = getClickedDayNumber(dayInfo))
{
alert("day number found : " + dayNumber);
}
function getClickedDayNumber(dayInfo)
{
dayNumber = dayInfo.indexOf("fc-day");
if(dayNumber != -1) //substring found
{
//normally any calendar month consists of "40" days, so this will definitely pick up its day number.
return parseInt(dayInfo.substring(dayNumber+6, dayNumber+8));
}
else return false;
}
基本上我发现我可以为一个值分配一个变量如果条件语句,并立即检查指定的值,就好像它是布尔值。
Basically I just found out that I can assign a variable to a value in an if condition statement, and immediately check the assigned value as if it is boolean.
为了更安全的赌注,我通常将其分成两行代码,首先分配然后检查变量,但是现在我发现了这个,我只是想知道在有经验的JavaScript开发人员看来它是否是好的做法?
For a safer bet, I usually separate that into two lines of code, assign first then check the variable, but now that I found this, I am just wondering whether is it good practice or not in the eyes of experienced JavaScript developers?
推荐答案
我不推荐它。问题是,在您尝试比较值时,它看起来像是一个常见错误,但使用单个 =
而不是 ==
或 ===
。例如,当你看到这个:
I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single =
instead of ==
or ===
. For example, when you see this:
if (value = someFunction()) {
...
}
你不知道这是他们的意图,还是他们打算写这个:
you don't know if that's what they meant to do, or if they intended to write this:
if (value == someFunction()) {
...
}
如果你真的想做适当的任务,我建议你做一个明确的比较:
If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:
if ((value = someFunction()) === <whatever truthy value you are expecting>) {
...
}
这篇关于在条件陈述中分配变量,良好实践与否?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!