三、AppleScript的循环与逻辑分支
2020-04-02 本文已影响0人
加盐白咖啡
条件语句
if true then
-- do something
end if
if false then
-- do something
end if
例:
set a to 20
set b to 30
if a = b then
set c to 10
else
set c to 20
end if

如何判断是否为“真”(true)
- 数的比较运算符
= is (or, is equal to) 等于
> is greater than 大于
< is greater than 小于
>= is greater than or equal to 大于等于
<= is less than or equal to 小于等于
并支持反义符号,如不大于,is not greater than。不等于 /= 或 is not
- 字符串的比较运算符
begins with (or, starts with) 以……开头
ends with 以……结尾
is equal to 一致
comes before 在……之前
comes after 在……之前
is in 在……之中
contains 包含
- 反义运算符
does not start with 不以……开头
does not contain 不以……结尾
is not in 不在……之内
等等。
- 比较运算符 "comes before" 和 "comes after" 对字符串逐字母比较,区分大小写
if "Jack" comes after "Rose" then
set a to 123
else
set a to 456
end if

- 忽略空格
set stringA to "Ja c k"
set stringB to "Jack"
ignoring white space
if stringA = stringB then beep
end ignoring
- 列表的比较运算符
begins with 以……开头
ends with 以……结尾
is equal to 一致
is in 在……之中
contains 包含
例子
set listA to {"a", "b", "c"}
if "a" is in listA then
set c to 123
else
set c to 456
end if

- 记录的比较运算符
is equal to(也可以使用 =) 一致
contains 包含
set recordA to {name:"Jack", age:20}
-- name of recordA is "Jack"
if recordA contains {name:"Jack"} then
set c to 123
end if

布尔数据的 与、或、非
-
and
set x to true
set y to true
set z to (x and y)

-
or
set x to true
set y to false
set z to (x or y)

-
not
set x to not true
set y to false
if x = y then
set z to 123
end if

循环
- repeat 重复 重复次数必须是整数,例
set repetitions to 2
-- repeat 2 times
repeat repetitions times
say "Hello world!"
end repeat
- 满足条件后重复执行下一步
set isRun to false
-- until 与 while 判断结果相反
repeat while isRun is false
say isRun
end repeat
- 从1读到5,步长默认为1
repeat with i from 1 to 5
say i
end repeat
- by 2 设置步长为2,如下
repeat with i from 1 to 5 by 2
say i
end repeat
repeat with aItem in itemList
end repeat
跳出循环, exit repeat
相当于break