我有以下 JavaScript 代码:
for (var x = 0; x < queue.length; x++) {
var song = new Song().loadJSON(queue[x]);
//Not already loaded
if (loaded.indexOf(song.url) == -1) {
addRow("play", song.url, song.title, song.album, song.artist);
loaded.push(song.url);
songs.push(song);
if (song.duration == 0) {
var audio = $("<audio>");
audio.attr("songid", songs.length - 1);
console.log("Writing:", audio.attr("songid"));
audio.on("durationchange", function () {
var id = audio.attr("songid");
console.log("Reading:", id);
songs[id].duration = audio[0].duration;
});
audio.attr("src", song.url);
}
}
}
这打印出来:
Writing: 0
Writing: 1
Writing: 2
(3x) Reading: 2
这让我相信在 for 循环的每次迭代中都会覆盖 songid 属性。我不确定这是怎么可能的,因为音频变量是每次迭代的本地变量。我究竟做错了什么?