问题描述
这应该是一个非常简单的问题,我只是在任何地方都找不到答案,所以我想节省一些时间在这里问.
This should be quite a simple question I just couldn't find the answer anywhere so thought I'd save myself some time and ask here.
我正在查看一些 javascript 代码并注意到以下形式的表达式:
I was looking at some javascript code and noticed an expression of the form:
a < b && (other maths statements);
其他数学语句只是分配变量和简单的东西.
The other maths statements are just assigning of variables and simple stuff.
我的问题是这样的.这是编写紧凑 if 语句的另一种方式吗?
My question is this. Is this another way to write compact if statements?
我知道那个语句?if-block:else-block;是一种方法,但作为 &&是短路和左联想这就是我能想到的.我知道你不能使用这种方法设置 else 块,但它非常简洁.
I know that statement?if-block:else-block; is one way to do it but as && is short-circuit and left-associative this is all I can think it would be. I know you can't have an else block with this method but it's pretty neat.
请有人验证一下我早上这个时候醒着吗?
Can someone just validate I'm awake at this time in the morning please.
谢谢,
推荐答案
是的,你可以做到.如果 a
小于 b
其他语句将被执行.
Yes, you can do it. If a
is less than b
the other statements are going to execute.
也就是说,你可能不应该这样做.与其尝试为自己节省少量的输入,不如使用更易读的代码,其目的是显而易见的.毕竟,如果您需要检查您没有误解它,其他可能需要阅读或修改您的代码的程序员可能会遇到同样的问题.
That said, you probably shouldn't do it. Rather than trying to save yourself a small amount of typing you should instead go with a more readable piece of code whose purpose is immediately obvious. After all, if you needed to check that you weren't misinterpreting it, other programmers who may have to read or modify your code could have the same problem.
如果您尝试执行多个分配,这也有一个陷阱,但中间分配之一是虚假"值.考虑这个例子:
There is also a pitfall with this if you were trying to do multiple assignments, but one of the middle assignments was for a "falsey" value. Consider this example:
a < b && (a = 1) && (b = 0) && (c = 3);
本质上,如果 a
小于 b
,则将 a
设置为 1, b
设置为 0 并且 c
为 3.但是,(b = 0)
返回 false(转换为布尔值时,0 被认为是 false),因此 (c = 3)
部分永远不会执行.显然,对于这个基本示例,任何对 JavaScript 有相当了解的人都可以计算出它会失败,但是如果 a
、b
和 c
来自其他地方,没有直接迹象表明它不会总是有效.
Essentially, if a
is less than b
, set a
to 1, b
to 0 and c
to 3. However, the (b = 0)
returns false (0 is considered false when converted to a boolean), so the (c = 3)
part never executes. Obviously with that basic example anybody who is reasonably knowledgeable about JavaScript could work out that it will fail, but if the values for a
, b
and c
were coming from elsewhere there'd be no immediate indication that it wouldn't always work.
这篇关于Javascript &&运算符 as if 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!