简化 if() 语句的语法或构造?
我正在寻找一种语义或语言构造来简化我的一些 if
语句。如果我有一个带有 or 的 if 语句,在两个值之间进行“选择”,我希望稍后在代码中可以使用该所选变量。
我将用伪代码编写:
if ( x or y ) {
function(z);
}
其中 z
是 x
或 y
的值,以触发 if是真的。否则,我
if ( x ) {
...
function(x);
}
if ( y ) {
...
function(y);
}
在该示例中编写 Now 时,重复的内容并不多,但在我的实际情况中,每个 if
块内大约有 6 行代码是相同的重复。所以我写了这样的内容:
if ( x ) {
z = x;
}
if ( y ) {
z = y;
}
if ( z ) {
...
function(z);
}
但这看起来太迂回了,我怀疑在某个地方,一些大师想出了一种很好的语法来制作单行 if
。语言中是否存在可以将触发值绑定到后续块中的变量的构造?这个结构叫什么?
我工作的实际情况是在PHP中,所以我意识到PHP可能没有这个能力。
I'm looking for a semantic or language construct that will simplify some of my if
statements. If I have an if statement with an or, where I 'choose' between two values, I'd like to have that chosen variable available later on in the code.
I'll write this in pseudo-code:
if ( x or y ) {
function(z);
}
Where z
is the value of x
or y
, whichever triggered the if
to be true. Otherwise I'm writing
if ( x ) {
...
function(x);
}
if ( y ) {
...
function(y);
}
Now in that example the duplication isn't much, but in my actual situation, there are about 6 lines of code that would be identical duplication within each if
block. So I write something like:
if ( x ) {
z = x;
}
if ( y ) {
z = y;
}
if ( z ) {
...
function(z);
}
But that just seems so roundabout I suspect that somewhere along the line some guru came up with a nice syntax to make a one-line if
. Is there a construct in a language anywhere where I can bind the triggering value into a variable in the subsequent block? What would this structure be called?
The actual situation I'm working in is in PHP, so I realize PHP may not have this capability.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,
就像 PHP 中宣传的那样。谢谢,睡梦人!
Actually, something like
Works as advertised in PHP. Thanks, slebetman!
对于这种具体情况。您可以使用
?
运算符:其内容为:z 是(如果 x 不为 false)x,否则是 y。
For this exact situation. You can use the
?
operator:Which reads: z is (if x is not false) x otherwise it is y.
在 Python(也包括 Ruby)中,如果表达式
x 或 y
为 true,则计算结果为x
,否则为y
。您可以将该语句写为f(x or y)
或z = x or y
。In Python (also Ruby), the expression
x or y
evaluates tox
if it is true, otherwisey
. You could write the statement asf(x or y)
, orz = x or y
.