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

AppleScript循环赋值异常:变量始终为0,求Repeat简化方案

问题原因与解决办法

你的代码里run script是在独立的执行环境里运行的,里面的test_01、test_02这些变量和主脚本里的同名变量完全不是同一个东西,所以赋值操作根本没影响到主脚本的变量,它们自然一直是初始的0。

下面给两种符合你需求的解决方案,都用Repeat循环替代了多IF语句:

方案一:用列表批量管理变量(推荐)

这种方式最简洁,不需要动态生成代码,直接操作列表元素即可:

set compteur to 1
set testList to {0, 0, 0} -- 对应test_01、test_02、test_03

repeat while compteur < 4
    set item compteur of testList to 11
    display dialog (compteur as text) & " - " & item 1 of testList & " - " & item 2 of testList & " - " & item 3 of testList
    set compteur to compteur + 1
end repeat

-- 如果之后需要单独的变量,从列表里提取即可
set test_01 to item 1 of testList
set test_02 to item 2 of testList
set test_03 to item 3 of testList

方案二:保留单独变量名的写法

如果一定要用test_01这类单独的变量名,可以通过脚本对象共享上下文,让run script能修改主脚本的变量:

set compteur to 1
set test_01 to 0
set test_02 to 0
set test_03 to 0

-- 创建脚本对象,把当前变量作为属性存入
set myScript to script
    property test_01 : test_01
    property test_02 : test_02
    property test_03 : test_03
end script

repeat while compteur < 4
    set valeur_de_fou to ("set test_0" & (compteur as text) & " of myScript to 11")
    run script valeur_de_fou
    -- 同步主脚本的变量值
    set test_01 to test_01 of myScript
    set test_02 to test_02 of myScript
    set test_03 to test_03 of myScript
    display dialog (compteur as text) & " - " & test_01 & " - " & test_02 & " - " & test_03
    set compteur to compteur + 1
end repeat

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:42:59