AppleScript是否有条件(三元)运算符的等价项?
由于熟悉编程,我缺少使用三元运算符分配变量的能力(即“如果某个值为真,则将变量设置为AppleScript是否有条件(三元)运算符的等价项?,applescript,ternary-operator,Applescript,Ternary Operator,由于熟悉编程,我缺少使用三元运算符分配变量的能力(即“如果某个值为真,则将变量设置为x,否则将其设置为y”)。我在想这样的事情: set my_string to (if a is 0 return "" else return " - substring") 这当然不起作用,我还没有发现类似的东西。有没有其他方法可以通过applescript实现这一点 if a is 0 then set my_string to "" else set my_string to " - s
x
,否则将其设置为y
”)。我在想这样的事情:
set my_string to (if a is 0 return "" else return " - substring")
这当然不起作用,我还没有发现类似的东西。有没有其他方法可以通过applescript实现这一点
if a is 0 then
set my_string to ""
else
set my_string to " - substring"
end if
或
看起来AppleScript不支持条件运算符,但您可以将list与两个元素一起使用。当然,一般来说,它不是很优雅:
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 'is 0' || echo 'is not 0'")
set b to (do shell script "test " & a & " -eq 0 || echo '- substring'")