如何在AppleScript中向函数传递方法、比较逻辑,复刻JS数组高阶方法?
AppleScript 实现JS数组高阶函数的正确方案
AppleScript 没有原生的匿名箭头函数语法,符合原生规范的最优实现方式是通过脚本对象(Script Object) 封装回调逻辑,作为参数传入你要实现的数组方法,完全不需要依赖shell调用拼接字符串的粗糙方案。
核心实现思路
把你要执行的回调逻辑封装在包含execute处理器的脚本对象中,数组方法内部遍历元素时主动调用execute即可,参数可以完全对齐JS的回调参数规范:当前元素、当前索引、原数组。
常用方法实现示例
1. forEach 实现
-- forEach 方法定义 on forEach(theArray, callback) repeat with i from 1 to count of theArray tell callback to execute(item i of theArray, i, theArray) end repeat end forEach
调用示例:
set theWords to {"These", "are", "test", "words"} -- 传入封装回调的脚本对象 forEach(theWords, script on execute(element, index, arr) log (index as string) & ": " & element end execute end script)
2. filter 实现
-- filter 方法定义 on filter(theArray, callback) set resultList to {} repeat with i from 1 to count of theArray set currentItem to item i of theArray tell callback to set isMatched to execute(currentItem, i, theArray) if isMatched then set end of resultList to currentItem end repeat return resultList end filter
调用示例(筛选长度大于6的单词):
set words to {"apple", "banana", "cherry", "watermelon"} set longWords to filter(words, script on execute(word, index, arr) return length of word > 6 end execute end script) -- 返回结果:{"banana", "watermelon"}
常见问题说明
你之前尝试的myFunc(log "Hello World")写法报错,是因为调用myFunc时会优先执行log "Hello World",将执行结果(空值)传入函数,而非将log逻辑本身作为参数传入,脚本对象的封装方式可以避免逻辑提前执行的问题。
你之前用shell拼接字符串的方案存在多个缺陷:遇到带空格的数组元素会解析错误、无法处理非字符串类型的元素、每次调用都要启动新的osascript进程性能极低,原生脚本对象方案可以完全规避这些问题。
内容的提问来源于stack exchange,提问作者gurkensaas
相关产品推荐
相关产品推荐

