Using “whose” on arrays in Javascript for Automation

前端 未结 4 1128
攒了一身酷
攒了一身酷 2021-02-10 12:40

Playing with the new JS for automation using Script Editor. I\'m getting an error on the final line of the following:

var iTunes = Application(\"iTunes\");
var s         


        
4条回答
  •  鱼传尺愫
    2021-02-10 13:10

    Based on the JavaScript for Automation Release Notes Mail.inbox.messages.whose(...) example, the following should work:

    var iTunes = Application('iTunes');
    var filtered = iTunes.sources.whose({name : 'Library'});
    

    The apparent goal for the "special whose method" with "an object containing the query" is to be efficient by only bringing select items (or item references) from the OS X object hierarchy into the resulting JavaScript array.

    However, ... the whose feature of JXA appeared to have some bugs in the earlier OS X v10.10 release.

    So, since the array in question is small (i.e. 2 items), filtering can be done fast & reliably on the JavaScript side after getting the elements as a JS array.

    Workaround Example 1

    var iTunes = Application('iTunes');
    var sources = iTunes.sources();
    var librarySource = null;
    for (key in sources) {
        var name = sources[key].name();
        if (name.localeCompare("Library") == 0) {
            librarySource = sources[key];
        }
    }
    

    Workaround Example 2

    var iTunes = Application('iTunes');
    var sources = iTunes.sources();
    function hasLibraryName(obj) {
        var name = obj.name();
        if (name.localeCompare("Library") == 0) {
            return true;
        }
        return false;
    }
    var filtered = sources.filter(hasLibraryName); 
    

提交回复
热议问题