【问题标题】:Does AppleScript have an equivalent for the conditional (ternary) operator?AppleScript 是否有条件(三元)运算符的等价物?
【发布时间】:2012-12-25 21:19:09
【问题描述】:

由于熟悉编程,我缺少使用三元运算符分配变量的能力(即“如果某事为真,则将变量设置为 x,否则将其设置为 y”)。我正在考虑类似的事情:

set my_string to (if a is 0 return "" else return " - substring")

这当然行不通,我还没有找到类似的东西。是否有另一种方法可以用 applescript 实现这一目标?

【问题讨论】:

  • 不管怎样,这个运算符的名字是“条件运算符”。它恰好是 a 三元运算符,但它不是 the 三元运算符,因为虽然它是目前唯一的三元运算符,但没有什么能阻止某人发明另一个三元运算符.

标签: applescript ternary-operator


【解决方案1】:

看起来 AppleScript 不支持条件运算符,但您可以为此目的使用带有两个元素的列表。当然,总的来说不是很优雅:

set my_string to item (((a is 0) as integer) + 1) of {"", " - substring"}

还有另一种方法:你可以使用 shell 脚本

set b to (do shell script "test " & a & " -eq 0 && echo 'is 0' || echo 'is not 0'")

我怎么能忘记这个? :)

在你的情况下它会更简单(因为如果根本没有回声,将返回一个空字符串)。

set b to (do shell script "test " & a & " -eq 0 || echo '- substring'")

【讨论】:

    【解决方案2】:
    if a is 0 then
        set my_string to ""
    else
        set my_string to " - substring"
    end if
    

    set a to 7
    
    set my_string to my subTern(a)
    
    on subTern(aLocalVar)
        if aLocalVar is 0 then return ""
        if aLocalVar is not 0 then return " - substring"
    end subTern
    

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 1970-01-01
      • 2013-04-19
      • 2023-03-12
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      相关资源
      最近更新 更多