【问题标题】:How to find the number of items in a variable? (AppleScript)如何查找变量中的项目数? (苹果脚本)
【发布时间】:2020-03-27 00:28:19
【问题描述】:

我正在尝试查找变量中的项目数,我尝试创建一些 while 循环来测试变量的项目是否存在,如果存在则转到下一个项目并测试它是否存在,重复此操作,直到项目不存在,然后显示当前项目编号,这应该是变量的最后一项。 这是我的代码:

    set stuff to "123456789"
    set x to "1"
    set num to item x of stuff
    if exists item x of stuff then
    repeat while exists item (x + 1) of stuff
        if exists (item x of stuff) then
            set x to (x + 1)
        else
            set num to x
        end if
    end repeat
    end if
    display dialog num

目前,当我运行此代码时,我收到错误: “无法获取“123456789”的第 10 项。” 据我了解,10 是该变量的最后一项,但该信息以错误消息的形式对我没有好处。在此先感谢

【问题讨论】:

    标签: applescript exists


    【解决方案1】:

    如何求变量中的项数? (AppleScript)

    线索就在问题中:

    set variable to "123456789"
    return the number of items in the variable --> 9
    

    正如 red_menace 所述,您还可以使用 length 属性(对于 listrecordtext 对象)或使用 count 来量化数据对象strong> 命令,在我看来这是多余的,因为它最终还是访问了length 属性。

    【讨论】:

    • 啊,非常感谢,显然我是一个 applescript 业余爱好者,因为我不知道这是可能的 xD。
    【解决方案2】:

    AppleScript 命令count 计算对象中元素的数量,例如count of stuff。此外,listrecordtext 等类也具有length 属性,例如length of stuff

    set stuff to "this is a test"
    set x to 0
    repeat with anItem in (get items of stuff)
        set x to x + 1 -- just using x to count
        log anItem
    end repeat
    display dialog "Number of items is " & x & return & "Count is " & (count stuff) & return & "Length is " & (length of stuff)
    

    请参阅AppleScript Language Guide 了解更多信息。

    【讨论】:

    • 感谢您提供的信息,这为我在未来项目中能够做的事情开辟了许多新的可能性,我知道我会使用它!
    猜你喜欢
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多