AppleScript学习笔记(四)条件语句和循环语句条件语句
if - el if - el语句块
AppleScript中的条件语句形式如下:
if 条件 then
...
el if 条件 then
...
el
...
end if
使⽤例如:
六要素-
- Numbers compare = <= >= /=
t num1 to 10
t num2 to 20
-- if num1 is num2 then
if num1 = num2 then
display dialog "num1 == num2"
恒大许家印
el
display dialog "num1 != num2"
end if
if num1 ≥ num2 then
1
劲脆鸡腿堡el if num1 ≤ num2 then
2
el
3
end if
最简单的形式是:
if 条件 then ...
注意上⾯的语句必须在同⼀⾏内完成。不需要也不能有end if出现。
使⽤例如:
if true then t x to 1
描写鸟的诗句
-- error
-
- if fal then t y to 0 end if
⽐较number
关于number之间的⽐较符号:= , <= , >= , /=(注意不是!=)分别代表等于,⼩于或等于,⼤于或等于,不等于。经过编译后⽐较符号会变成以下形式:
原书中对各种⽐较符号和对应的逻辑关键词列举如下:
⽐较string
string之间的⽐较使⽤逻辑关键词,这⾥就直接贴出原书的总结吧:
信息安全专业排名对于逻辑运算符⽤and,or,not表⽰与,或,⾮。
循环语句单亲家庭
循环语句有⼏种形式,类似于OC中的for循环,while循环,for in循环等。repeat X times
类似于for循环的形式如下:
repeat 重复的次数 times
...
end repeat
使⽤例如:
say "repeat"
end repeat
重复次数可以是⼀个数字变量,例如:
t repeatTimes to 10
repeat repeatTimes times
say "repeat"
end repeat
repeat from to by
另外⼀种类似for循环的形式为:
repeat with 计数变量 from 初始值 to ⽬标值 by 递增数
...
end repeat
by递增数部分可以缺省,如果缺省了那么每次计数变量加1。使⽤举例:
repeat with counter from 1 to 3
display dialog counter
end repeat
repeat with counter from 0 to 10 by 2
display dialog counter
end repeat
repeat while
类似于while循环的形式1:
repeat while 条件
双一流大学名单...
end repeat
使⽤例如:
repeat while counter ≠ 10
display dialog counter as string
t counter to counter + 2
end repeat
广州的大学排名repeat until
形式2:
repeat until 条件
...
end repeat
使⽤例如:
t counter to 0
repeat until counter = 10
display dialog counter as string
t counter to counter + 2
end repeat
repeat in
当然你可能猜到了,还有类似于for in循环的语句,可以⽤来遍历列表。形式如下:
repeat with 单个元素 in 集合
...
end repeat
使⽤例如:
t aList to {1, 2, 3}
repeat with anItem in aList
display dialog anItem as string
end repeat
有了条件语句和循环语句,可以按我们的逻辑思维去写代码了。
更多详细内容请参考《AppleScript for Absolute Starters》⼀书(中⽂名为《苹果脚本跟我学》)。