javascript - 如何在提示用户使用 AppleScript 从列表中选择后查找数组中的位置

标签 javascript arrays arraylist applescript

我不太明白这一点,我才刚刚开始编写脚本。为了解释,我想使用下面的代码来允许用户从列表中选择一个项目。然后,我想将他们选择的内容转换为列表中的数字位置。

例如,如果用户选择了 iPod,我希望它将他们的输入保存为 2 而不是 iPod。

这是我所拥有的:

set productList to {"iPad", "iPod", "iPhone", "Mac", "Apple TV", "Apple Watch", "Beats", "Apple Watch Edition", "Apple Watch Hermes"}
set yourProduct to choose from list of productList with prompt "Select your product: "

on listPosition(this_item, this_list)
    repeat with i from 1 to the count of this_list
        if item i of this_list is this_item then return i
    end repeat
    return 0
end listPosition

set item_num to my listPosition(yourProduct, productList)

最佳答案

虽然其他答案在发布此答案时确实会返回所选项目在列表中的位置,但它们不考虑可以使用 choose from list 进行的两种选择> command 按照您编码的方式。如图所示,您唯一需要做的就是修复当前的代码:

改变:

set yourProduct to choose from list of productList with prompt "Select your product: "

收件人:

try
    set yourProduct to item 1 of (choose from list of productList with prompt "Select your product:")
on error
    return
end try

它的作用是处理用户按下取消 按钮 和/或设置yourProduct> 到字符串,而不是列表,因为choose from list command if Cancel 没有被按下。然后您的 on listPosition(this_item, this_list) 处理程序 将在此特定用例中正常运行。

请注意,编写代码的方法通常不止一种,但通常最好使用 KISS 原则,尤其是在第一次学习如何编写代码时。

关于javascript - 如何在提示用户使用 AppleScript 从列表中选择后查找数组中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48123758/

相关文章:

javascript - 雅虎-OAuth2-SocialAPI : Not returning "Access-Control-Allow-Origin" in initial response

java - 如何按值对 Hashmap<String, Arraylist<String>> 类型的 Hashmap 进行排序?

java - 如何制作包含列表的java hashmap?

java - 如何将句子分成两部分?

javascript - AngularJS 中的条件

javascript - 获取段落对齐值

javascript - 我们如何在 React JavaScript 中使用管道?

c# - 在 Visual C# 中使用数组?

java - 引用变量数组

java - 使用字符串数组初始化 JComboBox 对象