且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除 Applescript 中的列表项

更新时间:2023-12-04 20:58:04

遗憾的是,AppleScript 中没有像 removeItemAtIndex 这样的高级函数.

Unfortunately there is no higher level function like removeItemAtIndex in AppleScript.

编写这样的函数非常麻烦,因为与其他编程/脚本语言不同,AppleScript 索引从 1 开始.

Writing such a function is quite cumbersome because unlike the other programming/script languages AppleScript indices start at 1.

例如

on removeItem from theList at theIndex
    if theIndex > (count theList) or theIndex is 0 then return theList
    if theIndex = 1 then
        return items 2 thru -1 of theList
    else if theIndex is (count theList) then
        return items 1 thru -2 of theList
    else
        tell theList to return items 1 thru (theIndex - 1) & items (theIndex + 1) thru -1
    end if
end removeItem

在 Foundation Framework 的帮助下容易一些(保持基于 1 的索引)

It's a bit easier with the help of the Foundation Framework (keeping the 1-based indices)

use AppleScript version "2.5"
use framework "Foundation"

on removeItem from theList at theIndex
    if theIndex > (count theList) or theIndex is 0 then return theList
    set mutableArray to current application's NSMutableArray's arrayWithArray:theList
    mutableArray's removeObjectAtIndex:(theIndex - 1)
    return mutableArray as list
end removeItem