You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AppleScript中获取用户选择列表项的数组位置

Fixing Your AppleScript: Getting the Selected Item's Position

Hey there! I see where the issue is here—let's get this working for you.

The problem with your current code is that the choose from list command returns a list object (even if you only select one item, it comes back as a single-element list like {"iPod"}), but your listPosition handler is expecting a single string item to compare against the product list. That's why it's returning 0 instead of the correct position!

Here's the corrected version of your script, with clear explanations:

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

-- First, handle the case where the user clicks "Cancel" (choose from list returns false)
if yourProduct is false then
    display dialog "You didn't select a product!" buttons {"OK"} default button 1
    return -- Exit the script early to avoid errors
end if

-- Extract the actual selected string from the returned list
set selectedItem to item 1 of yourProduct

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 -- Fallback if item isn't found (won't happen here since we picked from the list)
end listPosition

-- Now pass the single selected item to your handler
set item_num to my listPosition(selectedItem, productList)
-- Optional: Show the result to confirm it works
display dialog "Selected product position: " & item_num buttons {"OK"} default button 1

Key Fixes:

  • Added a check for when the user cancels the selection (prevents the script from throwing an error)
  • Pulled the actual selected string out of the yourProduct list using item 1 of yourProduct
  • Added a test dialog to let you see the position number clearly

Now when you select "iPod", item_num will correctly be set to 2, just like you wanted!

内容的提问来源于stack exchange,提问作者NewbieD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:25:07