简化 if() 语句的语法或构造?

发布于 2024-09-19 04:15:20 字数 730 浏览 9 评论 0原文

我正在寻找一种语义或语言构造来简化我的一些 if 语句。如果我有一个带有 or 的 if 语句,在两个值之间进行“选择”,我希望稍后在代码中可以使用该所选变量。

我将用伪代码编写:

if ( x or y ) {
    function(z);
}

其中 zxy 的值,以触发 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

季末如歌 2024-09-26 04:15:29

实际上,

if ( $z = ( $x ? $x : $y ) ) {
    function($z);
}

就像 PHP 中宣传的那样。谢谢,睡梦人!

Actually, something like

if ( $z = ( $x ? $x : $y ) ) {
    function($z);
}

Works as advertised in PHP. Thanks, slebetman!

宛菡 2024-09-26 04:15:27

对于这种具体情况。您可以使用 ? 运算符:

z = x ? x : y;

其内容为:z 是(如果 x 不为 false)x,否则是 y。

For this exact situation. You can use the ? operator:

z = x ? x : y;

Which reads: z is (if x is not false) x otherwise it is y.

调妓 2024-09-26 04:15:26

在 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 to x if it is true, otherwise y. You could write the statement as f(x or y), or z = x or y.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文