【问题标题】:Why doesn't my JavaScript return the array to an AppleScript list?为什么我的 JavaScript 不将数组返回到 AppleScript 列表?
【发布时间】:2017-10-04 23:40:48
【问题描述】:
tell application "Safari"
    set theVar to (do JavaScript "
var a = 
document.getElementById('unitsdiv').getElementsByClassName('even');
var b = []
for (var i = 0; i < a.length; i++) {
    b[i] = a[i].textContent;
};
console.log(b.length);  \\ Returns 2
console.log(b[1]);      \\ Returns item 2 of Array
console.log(b[0]);      \\ Returns item 1 of Array
b;                      \\ Shows both items in Safari Console
") in document 1
end tell

log theVar -- Missing Value

代码在 Safari 控制台中按预期工作。我还尝试在使用 set theVar to {} 运行 do Javascript 命令之前初始化列表,但无济于事。任何帮助,将不胜感激。

这似乎返回值之一

tell application "Safari"
    tell document 1
    set theVar to (do JavaScript "
var a = document.getElementById('unitsdiv').getElementsByClassName('even');
var b = []; 
for (var i = 0; i < a.length; i++) 
{ b[i] = a[i].textContent; };
console.log(b.length);
console.log(b[1]); 
console.log(b[0]);
b[0];")
end tell
end tell
log theVar

如果我尝试在 javascript 代码末尾将数组选择器 [0]b 中取出,然后告诉 AppleScript 到 log theVar,它会引发一个错误,即 theVar 未定义。

【问题讨论】:

    标签: javascript applescript


    【解决方案1】:

    我能想出的唯一解决方案并不可怕,以防其他人遇到这个问题

    -- Function that allows you to pass a number from applescript to javascript to grab an item of an array. 
    
    on theFunc(theNum)
       tell application "Safari"
            tell document 1
                set a to do JavaScript "var a = 
    document.getElementById('unitsdiv').getElementsByClassName('even');
    var b = []
    for (var i = 0; i < a.length; i++) {
         b[i] = a[i].textContent;
    };
     b[" & theNum & "];"
            end tell
        end tell
    -- returns item theNum of the Javascript array
         return a
    end theFunc
    
    -- Initialize an array to contain the items returned from the loop below
    set theArray to {}
    -- Initialize a number to increment while the condition is true and pass to the function in the loop below
    set theNum to 0
    
    -- Use some string that is in each of items of the array, if you don\'t have a specific string, you could try to set it to something like \"does not contain \"missing value\" maybe, or length is something etc
     repeat while theFunc(theNum) contains "LB" 
        set the end of theArray to theFunc(theNum)
        set theNum to theNum + 1
    end repeat
    
    -- proof that the variable is an array and contains multiple items
    repeat with a from 1 to the count of theArray
        log item a of theArray
    end repeat
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多