Javascript 在 if 条件语句中分配变量,好的做法与否?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2576571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign variable in if condition statement, good practice or not?
提问by Michael Mao
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:
一年前,我从 Java 等经典 OO 语言转向了 JavaScript。在 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.
基本上我刚刚发现我可以在 if 条件语句中将一个变量分配给一个值,并立即检查分配的值,就好像它是布尔值一样。
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?
为了更安全,我通常将其分成两行代码,先赋值然后检查变量,但现在我发现了这一点,我只是想知道在有经验的 JavaScript 开发人员眼中这是否是一种好的做法?
回答by Matthew Crumley
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:
我不会推荐它。问题是,当您尝试比较值时,它看起来像是一个常见错误,但使用单个=而不是==or ===。例如,当您看到以下内容时:
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>) {
...
}
回答by Adrian Bartholomew
I see no proof that it is not good practice. Yes, it may look like a mistake but that is easily remedied by judicious commenting. Take for instance:
我看不到任何证据表明这不是好的做法。是的,它可能看起来像一个错误,但通过明智的评论很容易纠正。举个例子:
if (x = processorIntensiveFunction()) { // declaration inside if intended
alert(x);
}
Why should that function be allowed to run a 2nd time with:
为什么应该允许该函数第二次运行:
alert(processorIntensiveFunction());
Because the first version LOOKS bad? I cannot agree with that logic.
因为第一个版本看起来很糟糕?我不能同意这种逻辑。
回答by Ming-Tang
I did it many times. To bypass the JavaScript warning, I add two parens:
我做了很多次。为了绕过 JavaScript 警告,我添加了两个括号:
if ((result = get_something())) { }
You should avoid it, if you really want to use it, write a comment above it saying what you are doing.
你应该避免它,如果你真的想使用它,在它上面写一个评论,说明你在做什么。
回答by Ben Zotto
You can do this in Java too. And no, it's not a good practice. :)
您也可以在 Java 中执行此操作。不,这不是一个好习惯。:)
(And use the ===in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)
(并===在 Javascript 中使用用于类型化相等。阅读 Crockford 的关于 JS 的 The Good Parts 书。)
回答by Daniel Kvist
There is one case when you do it, with while-loops.
When reading files, you usualy do like this:
当你使用while-loops时,有一种情况。
读取文件时,您通常会这样做:
void readFile(String pathToFile) {
// Create a FileInputStream object
FileInputStream fileIn = null;
try {
// Create the FileInputStream
fileIn = new FileInputStream(pathToFile);
// Create a variable to store the current line's text in
String currentLine;
// While the file has lines left, read the next line,
// store it in the variable and do whatever is in the loop
while((currentLine = in.readLine()) != null) {
// Print out the current line in the console
// (you can do whatever you want with the line. this is just an example)
System.out.println(currentLine);
}
} catch(IOException e) {
// Handle exception
} finally {
try {
// Close the FileInputStream
fileIn.close();
} catch(IOException e) {
// Handle exception
}
}
}
Look at the while-loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if-statement, but I guess a while loop can be included in your question as well.
查看while第 9 行的-loop。在那里,读取一个新行并将其存储在变量中,然后运行循环的内容。我知道这不是 -if语句,但我想您的问题中也可以包含一个 while 循环。
The reason to this is that when using a FileInputStream, every time you call FileInputStream.readLine(), it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != nullwithout assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null, and then called it from inside of the loop too, you would only get every second line.
这样做的原因是,当使用 a 时FileInputStream,每次调用时FileInputStream.readLine(),它都会读取文件中的下一行,因此,如果您从循环中调用它fileIn.readLine() != null而不分配变量,而不是调用(currentLine = fileIn.readLine()) != null,然后从在循环内部,你只会得到每第二行。
Hope you understand, and good luck!
希望你理解,祝你好运!
回答by Nitrodist
You can do assignments within if statements in Java as well. A good example would be reading something in and writing it out:
您也可以在 Java 中的 if 语句中进行赋值。一个很好的例子是读入并写出:
http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new
http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new
The code:
编码:
// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
回答by allan
If you were to refer to Martin Fowlers book Refactoring improving the design of existing code ! Then there are several cases where it would be good practice eg. long complex conditionals to use a function or method call to assert your case:
如果您要参考 Martin Fowlers 的书重构改进现有代码的设计!然后有几种情况,这将是一种很好的做法,例如。使用函数或方法调用来断言您的案例的长复杂条件:
"Motivation
One of the most common areas of complexity in a program lies in complex conditional logic. As you write code to test conditions and to do various things depending on various conditions, you quickly end up with a pretty long method. Length of a method is in itself a factor that makes it harder to read, but conditions increase the difficulty. The problem usually lies in the fact that the code, both in the condition checks and in the actions, tells you what happens but can easily obscure why it happens.
As with any large block of code, you can make your intention clearer by decomposing it and replacing chunks of code with a method call named after the intention of that block of code. > With conditions you can receive further benefit by doing this for the conditional part and each of the alternatives. This way you highlight the condition and make it clearly what you > are branching on. You also highlight the reason for the branching."
“动机
程序中最常见的复杂领域之一在于复杂的条件逻辑。当您编写代码来测试条件并根据各种条件执行各种操作时,您很快就会得到一个相当长的方法。方法的长度本身就是一个使其更难阅读的因素,但条件会增加难度。问题通常在于这样一个事实,即条件检查和操作中的代码会告诉您发生了什么,但很容易掩盖其发生的原因。
与任何大型代码块一样,您可以通过分解它并将代码块替换为以该代码块的意图命名的方法调用来使您的意图更加清晰。> 有了条件,您可以通过对条件部分和每个备选方案执行此操作来获得更多好处。通过这种方式,您可以突出显示条件,并清楚地说明您 > 正在分支的内容。您还强调了分支的原因。”
And yes his answer is also valid for Java implementations. It does not assign the conditional function to a variable though in the examples.
是的,他的回答也适用于 Java 实现。尽管在示例中,它不会将条件函数分配给变量。
回答by thethanghn
It's not good practice. You soon will get confused about it. It looks similiar to a common error: misuse "=" and "==" operators.
这不是一个好习惯。你很快就会对此感到困惑。它看起来类似于一个常见的错误:误用“=”和“==”运算符。
You should break it into 2 lines of codes. It not only helps to make the code clearer, but also easy to refactor in the future. Imagine that you change the IF condition? You may accidently remove the line and your variable no longer get the value assigned to it.
你应该把它分成两行代码。它不仅有助于使代码更清晰,而且在将来易于重构。想象一下,你改变了 IF 条件?您可能会不小心删除该行,并且您的变量不再获得分配给它的值。
回答by Justin Ethier
I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.
我认为这更像是一种老式的 C 风格;这在 JavaScript 中并不是很好的做法,所以你应该避免它。
回答by Joseph Le Brech
you could do something like so:
你可以这样做:
if (value = /* sic */ some_function()){
use_value(value)
}

