如何在 VBScript for Classic-ASP 中执行单行 If 语句? [英] How to do a single line If statement in VBScript for Classic-ASP?

查看:18
本文介绍了如何在 VBScript for Classic-ASP 中执行单行 If 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单行 if 语句"存在于 C# 和 VB.NET 中,就像在许多其他编程和脚本语言中一样,格式如下

The "single line if statement" exists in C# and VB.NET as in many other programming and script languages in the following format

lunchLocation = (dayOfTheWeek == "Tuesday") ? "Fuddruckers" : "Food Court";

有谁知道 VBScript 中是否有,确切的语法是什么?

does anyone know if there is even in VBScript and what's the extact syntax?

推荐答案

条件三元运算符不是开箱即用的,但在 VBScript 中创建自己的版本非常容易:

The conditional ternary operator doesn't exist out of the box, but it's pretty easy to create your own version in VBScript:

Function IIf(bClause, sTrue, sFalse)
    If CBool(bClause) Then
        IIf = sTrue
    Else 
        IIf = sFalse
    End If
End Function

然后您可以按照您的示例使用它:

You can then use this, as per your example:

lunchLocation = IIf(dayOfTheWeek = "Tuesday", "Fuddruckers", "Food Court")

与使用单行 If/Then/Else 相比,它的优点在于它可以直接与其他字符串连接.在一行中使用 If/Then/Else 必须是该行的唯一语句.

The advantage of this over using a single line If/Then/Else is that it can be directly concatenated with other strings. Using If/Then/Else on a single line must be the only statement on that line.

对此没有错误检查,并且该函数需要一个格式良好的表达式,该表达式可以计算为作为子句传入的布尔值.有关更复杂和全面的答案,请参见下文.希望这个简单的回答巧妙地展示了答案背后的逻辑.

There is no error checking on this, and the function expects a well formed expression that can be evaluated to a boolean passed in as the clause. For a more complicated and comprehensive answer see below. Hopefully this simple response neatly demonstrates the logic behind the answer though.

还值得注意的是,与真正的三元运算符不同,sTruesFalse 参数都将被评估,而不管 bClause<的值如何/代码>.如果您像问题中那样将它与字符串一起使用,这很好,但是如果您将函数作为第二个和第三个参数传入,请务必小心!

It's also worth noting that unlike a real ternary operator, both the sTrue and sFalse parameters will be evaluated regardless of the value of bClause. This is fine if you use it with strings as in the question, but be very careful if you pass in functions as the second and third parameters!

这篇关于如何在 VBScript for Classic-ASP 中执行单行 If 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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