Applescript语法整理(1)

编写基础

  • 定义变量用set...to... 获取变量用get

set value to 5
get value

  • 计算

set a to 3
set b to 5
set c to ab
-- 常用的运算符有:+、-、
、/、^、 对的,加减乘除乘方

  • 注释用--

-- 这是注释

  • 用tell告诉应用程序怎么做end tell 结束这个过程

-- 清空废纸篓
tell application "Finder"
empty the trash
end tell

  • 打开脚本编辑器,文件->打开字典->选择应用,可以查看各种属性和命令
  • AppleScript没有结构体,所以很难做复杂的工程,定义函数并调用

-- 声明
on sayHello ()
say "hello"
end sayHello
-- 调用
sayHello()

字符串操作

  • 拼接 使用 & 拼接字符串

-- 字符串与字符串拼接
set str to "1234" & "4567"
-- 字符串与列表拼接
set str to "hello" & {"world"}
-- 列表与列表拼接
set str to {"hello"} & {"world"}

  • 查看字符串长度 the length of 用来获取字符串的长度

set theLength to the length of "Neal"

  • 类型转换

-- 字符串与数字类型转换
set strToNumber to "16" as number
set numToStr to 12 as string
-- 字符串与列表转换
set strList to "111" as list

  • 分割

-- 使用itemized关键字可以将字符串分割成字符并组成新的列表
set itemized to every character of strAndStr
-- 通过AppleScript's text item delimiters 指定分割符,通过every text item of实现分割
set AppleScript's text item delimiters to " "
set listAfterDelimiter to every text item of strAndStr

列表

  • 基本操作

-- 声明列表
set firstList to {11, 230, "black", 789, 453, "world", 111}
-- 更改列表指定位置元素
set item 2 of firstList to "hello"
set the third item of firstList to "234"
-- 随机获取列表中一个元素
set randomX to some item of firstList
-- 获取列表最后一个元素
set lastItem to the last item of firstList
-- 获取列表第一个元素
set firstItem to the first item of firstList
-- 负数表示从列表尾端获取数据
set temp to item -2 of firstList
-- 获取列表2到4位返回列表
set shortList to items 2 through 4 of firstList
-- 逆向获取子列表
set reversedList to reverse of firstList
-- 获取列表数量
set listCount to the count of firstList
-- 为列表末尾添加数据
set the end of longList to 10

Record

  • 基本操作

-- 声明
set tempRecord to {name: "张三丰", age: 100, desc: "太极"}
-- 更改
set tempName to the name of tempRecord
-- 使用value创建新的Record
set newRecord to {newName: name of tempRecord}
-- 数量
set recordCount to the count of tempRecord

条件语句

if 条件 then
else if 条件 then
else
end if
-- 条件判断 英文好点是可以蒙出来的
-- 以...开头
begins with 或starts with
-- 不以。。。开头
does not start with
-- 以。。。结束
ends with
-- 相等
is equal to
-- 在。。。之前。比较两字符的ascii码
comes before
-- 在。。。之后。比较两字符的ascii码
comes after
-- 在。。。之中
is in
-- 不在。。。中
is not in
-- 包含
contains
-- 不包含
does not contain

循环语句

  • 1

set sum to 0
set i to 0
repeat 100 times
set i to i + 1
set sum to sum + i
end repeat

  • 2

repeat with counter from 0 to 10 by 1
display dialog counter
end repeat

  • 3

repeat while counter = 10
display dialog counter as string
set counter to counter + 2
end repeat

  • 4

repeat until counter = 10
display dialog counter as string
set counter to counter + 2
end repeat

  • 5

set aList to {1, 2, 3, 4}
repeat with anItem in aList
display dialog anItem as string
end repeat

参考

https://www.aliyun.com/jiaocheng/363028.html?spm=5176.100033.1.19.46de67eeTLYpbB
https://www.aliyun.com/jiaocheng/363027.html?spm=5176.100033.1.19.7a156d1fl5Frpv

你可能感兴趣的:(Applescript语法整理(1))