简体   繁体   English

遍历数组时的错误处理

[英]Error handling when iterating through an array

Newbie here. 新手在这里。 I've written a simple test function that iterates through a bunch of song listings and for each one tries to fetch the album cover image from the Last.fm API. 我编写了一个简单的测试函数,该函数遍历一堆歌曲列表,每个函数都尝试从Last.fm API中获取专辑封面图像。 If it doesn't work, it's supposed to display the track and artist name in the console. 如果不起作用,应该在控制台中显示曲目和歌手姓名。 When I run it, however, it always displays the same artist/track pair, namely the last one iterated through, not the specific one that triggered the error. 但是,当我运行它时,它总是显示相同的艺术家/曲目对,即最后一个重复的对,而不是触发错误的特定对。 I'm not sure what's going on. 我不确定发生了什么。

$(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)"},
 .....
 }

Have a look at the difference between for and for in 看看for和for之间的区别

I think in this case you should use a standard for loop. 我认为在这种情况下,您应该使用标准的for循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM