我想将这个工作 AppleScript 转换为 JS:
tell application "Music"
repeat with theTrack in (every track whose name is "Baby")
tell theTrack
set name to do shell script ¬
"echo " & quoted form of (name & "") & ¬
" | sed 's/^\\(.\\)\\(.\\)/\\2\\1/'"
end tell
end repeat
end tell
但由于“无法获取对象”错误,我什至无法获取曲目:
const music = Application("Music");
const tracks = music.tracks.whose({ name: "Baby" });
console.log(tracks);
app = Application("Music")
app.tracks.whose({_match: [ObjectSpecifier().name, "Baby"]}).tracks.byName("Symbol.toPrimitive")()
--> Error -1728: Can't get object.
如何将 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;
});