【问题标题】:How to check the value of wscript.arguments(0) without two if statements如何在没有两个 if 语句的情况下检查 wscript.arguments(0) 的值
【发布时间】:2013-11-28 09:51:09
【问题描述】:

我希望能够检查第一个传递给 Windows 脚本的参数的值。但我希望能够做到这一点,即如果没有传递参数,脚本不会给出运行时错误。

这只是一个好奇的问题,因为我可以让我的脚本使用两个 if 语句,但我想知道是否有办法只用一个(比如

monthly = false

if wscript.arguments.count > 0 then 

    if wscript.arguments(0) = "monthly" then

        monthly = true

    end if

end if

如果能这样就更整洁了……

if wscript.arguments.count > 0 and wscript.arguments(0) = "Monthly" then

    monthly = true

end if

但这会导致下标超出范围错误,因为脚本引擎正在尝试检查不存在的数组项的值。

我知道我可以在 PHP 中进行这种类型的检查 (if(isset($_POST['somevariable'])) && $_POST['somevariable'] == 'somevalue')

【问题讨论】:

  • 也许是个愚蠢的问题,但这是 VBScript 吗?
  • 是的,我将问题标记为 wscript,默认情况下不是 vbscript 吗?
  • 老实说,我并不完全有资格这样做。但是在 VBScript 中允许 If(cond1 And cond2)
  • 但如果 cond1 为 false,解析器仍会检查 cond2,在这种特殊情况下,检查 cond2 时会抛出下标超出范围错误。我知道您可以在 if 语句中检查多个变量。但这个特殊情况是不同的。我已经编辑了我的问题,使其更加清晰。如果第一个值为 false,则第二个值不存在。
  • 我想我真正要问的是,在该位置可能没有数组项的情况下,检查数组项值的“干净”方法是什么。

标签: wsh


【解决方案1】:

答案是你做不到,因为 VBScript 没有短路和运算符。

出于好奇,您可以查看以下链接:

http://en.wikipedia.org/wiki/Short-circuit_evaluation

VBScript conditional short-circuiting workaround

【讨论】:

  • 谢谢。想了那么多。但我有点强迫症,所以我喜欢探索“干净”的做事方式,然后再解决自己在解决编码问题时首先遇到的有点尴尬的方式。
  • “select case”被标记为替换,但它看起来并不像嵌套的那样干净,所以我认为它并不重要。
【解决方案2】:

如果对参数有多个测试,则不必不断重复双 if/then 条件。

对参数进行一次测试并将其放入变量中。之后的所有其他检查只需要一个 if/then 对变量的检查。或者使用 'case' 来选择。

dim argument
if wscript.arguments.count > 0 then
    argument = wscript.arguments(0)
end if

if argument = "test1" then
  msgbox "test1"
end if

if argument = "test2" then
  msgbox "test2"
end if

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-28
    • 2018-10-25
    • 2017-09-03
    • 1970-01-01
    • 2022-11-29
    • 1970-01-01
    • 2014-11-25
    • 2019-03-06
    相关资源
    最近更新 更多