使用Javascript和放大器;&安培;运营商作为if语句? [英] Javascript && operator as if statement?

查看:113
本文介绍了使用Javascript和放大器;&安培;运营商作为if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是一个相当简单的问题我无法找到答案任何地方,所以以为我会拯救自己一些时间,并要求在这里。

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 code和注意到形式的前pression:

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?

我知道,如果语句块:别的块;就是做这件事,但因为与放大器;&安培;是短路和左关联,这是所有我能想到这将是。我知道你不能用这种方法一个else块,但它是pretty整洁。

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.

这是说,你可能不应的做到这一点。而不是试图自己节省打字您应该用更具可读性一块code的,其目的是显而易见的走量小。毕竟,如果你需要检查一下你是不是misinter preting吧,谁可能要读取或修改您的code可能有同样的问题,其他程序员。

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.

有也跟这个有陷阱,如果你试图做多任务,但中间的任务之一是为一个falsey的价值。考虑这个例子:

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被认为是假的),因此(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和放大器;&安培;运营商作为if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆