我想将这个工作 AppleScript 转换为 JS:
tell application "Music"
repeat with theTrack in (every track whose name is "Baby" or name is "aBby")
tell theTrack
set name to do shell script ¬
"echo " & quoted form of (name & "") & ¬
" | sed 's/^\\([aB]\\)\\([aB]\\)/\\2\\1/'"
end tell
end repeat
end tell
但是我选择曲目的代码不起作用:
const music = Application("Music");
const tracks = music.tracks.whose({ _or: [ {name: "Baby"}, {name: "aBby"} ] })();
tracks.forEach(track => {
track.name = track.name().replace(/^([aB])([aB])/, '$2$1');
});
app = Application("Music")
app.tracks.whose({_or: [{_match: [ObjectSpecifier().name, "Baby"]}, {_match: [ObjectSpecifier().name, "aBby"]}]})()
Result:
Error -1700: Can't convert types.
当我摆脱
_or
、...tracks.whose({ name: "Baby" })
时,它就起作用了。
如何将 AppleScript 转换为 JavaScript for Automation 脚本?
您遇到的问题似乎是由于 JavaScript for Automation (JXA) API 与 who 和其他对象说明符等属性交互的方式造成的。这与 AppleScript 处理它们的方式略有不同。
const music = Application("Music");
// Retrieve the tracks whose name is "Baby"
const tracks = music.tracks.whose({ name: "Baby" })();
// Iterate through the matching tracks and rename them
tracks.forEach(track => {
// Get the current name of the track
const currentName = track.name();
// Perform the shell script operation using JavaScript's `doShellScript` function
const newName = Application.currentApplication().doShellScript(`echo "${currentName}" | sed 's/^\\(.\\)\\(.\\)/\\2\\1/'`);
// Set the new name to the track
track.name = newName;
});