Cor*_*ley 1 string applescript list
我想知道是否有一种简便的方法可以将AppleScript列表转换为分隔每个项目的字符串。我可以以一种我想要的更长的方式来实现这一目标,所以我想知道是否有一种简单的方法可以实现这一目标。基本上,我想获取一个清单,例如{1,2,3}将其转换为string "1, 2, 3"。我可以做类似下面的事情,但是在结果字符串后面导致逗号:
set myList to {"1.0", "1.1", "1.2"}
set Final to ""
if (get count of myList) > 1 then
repeat with theItem in myList
set Final to Final & theItem & ", "
end repeat
end if
Run Code Online (Sandbox Code Playgroud)
将列表转换为字符串的情况非常频繁,因此您最好创建一个子例程。
on list2string(theList, theDelimiter)
-- First, we store in a variable the current delimiter to restore it later
set theBackup to AppleScript's text item delimiters
-- Set the new delimiter
set AppleScript's text item delimiters to theDelimiter
-- Perform the conversion
set theString to theList as string
-- Restore the original delimiter
set AppleScript's text item delimiters to theBackup
return theString
end list2string
-- Example of use
set theList to {"red", "green", "blue"}
display dialog list2string(theList, ", ")
display dialog list2string(theList, "\n")
Run Code Online (Sandbox Code Playgroud)
有一个简短的方法,它叫做 text item delimiters
set myList to {"1.0", "1.1", "1.2"}
set saveTID to text item delimiters
set text item delimiters to ", "
set Final to myList as text
set text item delimiters to saveTID
Run Code Online (Sandbox Code Playgroud)