迭代数组时的错误处理

时间:2013-07-29 22:59:12

标签: javascript jquery error-handling iteration

新手在这里。我编写了一个简单的测试函数,它迭代了一堆歌曲列表,并且每个人试图从Last.fm API中获取专辑封面图像。如果它不起作用,它应该在控制台中显示曲目和艺术家名称。但是,当我运行它时,它总是显示相同的艺术家/轨道对,即最后一个迭代通过,而不是触发错误的特定一对。我不确定发生了什么。

$(document).ready(function(){
array = []
for (var item in billboard) {
  var track = billboard[item]['song'];
  var artist = billboard[item]['artist'];
  $.getJSON("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=myAPIkey&artist=" + artist + "&track=" + track + "&format=json&callback=?", function(data) {
      try{
        image = data.track.album.image[2]['#text'];
      }
      catch (err) {
        console.log(track + " - " artist);
        }
      });
    }
});


 var billboard = {

 "7-12-1986": {"artist": "Simply Red", "song": "Holding Back The Years"},
"6-28-1986": {"artist": "Patti LaBelle ", "song": "On My Own"},
 "7-5-1986": {"artist": "Billy Ocean", "song": "There'll Be Sad Songs (To Make You Cry)"},
 .....
 }

1 个答案:

答案 0 :(得分:0)

查看for and for in

之间的区别

我认为在这种情况下你应该使用标准for循环。