假设我有一组10个对象,其中一个对象需要从API中提取的其他信息,通过Javascript调用。在我的例子中,这个对象是一个Soundcloud嵌入,我需要从他们的API获得更多信息。
使用jQuery,我可以使用$.getJSON
并将已解析的值推送到全局数组中,但这似乎并不能保证在没有大量拼接代码的情况下将其放置在正确的顺序中。 / p>
保持列表顺序的最佳做法是什么?
示例:
var embeds = [{type: "mp3", url: "http://example.com/song.mp3", artist: "Artist"},
{type: "mp3", url: "http://anotherexample.com/song.mp3", artist: "Artist 2"},
{type: "soundcloud", url: "http://soundcloud.com/summergirlfriends/shockwaves"}];
for(e in embeds) {
if(embeds[e].type == "soundcloud") {
// here is where i need to call the SC API and do something with the results
}
}
答案 0 :(得分:4)
如果我理解正确的话,我认为您正在寻找的是一个关闭,以确保您正在修改正确的嵌入:
var embeds = [{type: "mp3", url: "http://example.com/song.mp3", artist: "Artist"},
{type: "mp3", url: "http://anotherexample.com/song.mp3", artist: "Artist 2"},
{type: "soundcloud", url: "http://soundcloud.com/summergirlfriends/shockwaves"}];
for(var i=0;i<embeds.length;i++) {
if(embeds[i].type == "soundcloud") {
(function(embed){
$.ajax({
//...
success:function(newData){
embed['additionalData']=newData;
console.log(embeds);
}
});
})(embeds[i])
}
}