获取列表苹果脚本中所选项目的索引

getting an index of a selected item in a list apple script

我正在尝试编写一个包含大列表的 apple 脚本,我想提示用户 select 列表中的一个项目,然后脚本应该显示该项目的索引。让脚本提示用户从列表中 select 不是问题,但我无法获得 selected 列表项的索引。

这是我到目前为止尝试过的示例代码和循环

set cities to {"New York", "Portland", "Los Angelles", "San Francisco", "Sacramento", "Honolulu", "Jefferson City", "Olimpia"}
set city_chooser to choose from list cities
set item_number to 0
repeat with i from 1 to number of items in cities
    set item_number to item_number + 1
    if i = city_chooser then
        exit repeat
    end if
end repeat
display dialog item_number

它只是给我列表中的项目数。

Vanilla AppleScript 不提供 indexOfObject API。三种方式:

  1. 一个基于索引的循环,它在找到对象时迭代列表和 returns 索引。
  2. 将列表桥接到 AppleScriptObjC 以使用 NSArrayindexOfObject API。
  3. 如果列表是排序的二进制搜索算法,速度非常快。

第四种方法是用这种格式填充列表

1 Foo
2 Bar
3 Baz

并通过数字前缀获取索引,但这对于大型列表来说非常麻烦。


编辑:

代码中存在一些问题。主要的两个是 choose from list returns 一个列表(或 false)并且您正在将字符串与索引变量(一个整数)进行比较。

试试这个

set cities to {"New York", "Portland", "Los Angeles", "San Francisco", "Sacramento", "Honolulu", "Jefferson City", "Olympia"}
set city_chooser to choose from list cities
if city_chooser is false then return
set city_chooser to item 1 of city_chooser
repeat with i from 1 to (count cities)
    set city to item i of cities
    if city = city_chooser then exit repeat
end repeat
display dialog i

您可以像这样使用 AppleScriptObjC 检索索引:

使用 AppleScript 版本“2.4” 使用框架“Foundation”

property NSArray : class "NSArray"

-- usage example with different data types. ASOC handles all the conversions
my firstIndexOf:3 inList:{"a", "hello", 3, date "Wednesday, February 12, 2020 at 12:00:00 AM", true}

on firstIndexOf:anItem inList:aList
    set anArray to NSArray's arrayWithArray:aList
    return (anArray's indexOfObject:anItem) + 1
end firstIndexOf:inList:

概述的重复循环 vadian 适用于大多数情况。您只想将它​​用于大型列表,其中 ASOC 的性能优势开始变得有意义。