gpt4 book ai didi

javascript - 为什么我的数组在JS中建好数组后调用函数时显示为空

转载 作者:行者123 更新时间:2023-11-28 21:21:53 25 4
gpt4 key购买 nike

// variables to be used throughout
var videos = new Array();

// similar artist/bands
function similarTo(who) {
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&artist='+who+'&limit=20&api_key=b25b959554ed76058ac220b7b2e0a026&format=json&callback=?', function(data) {
$.each(data , function(i,similars) {
$.each(similars.artist, function(c, artist) {
$.getJSON('http://gdata.youtube.com/feeds/api/videos?q='+artist.name+'&orderby=relevance&start-index=1&max-results=1&v=2&alt=json-in-script&callback=?', function(data) {
$.each(data.feed.entry, function(i,video) {
videos.push({
id: video.id.$t.split(":")[3],
title: video.title.$t
});
});
});
});
initPlaylist();
});
});
}

// start the playlist
function initPlaylist() {
$('#ytplayerid').load('includes/ytplayer.php?track=' + videos[currenttrack].id);
$('#player span').html(videos[currenttrack].title);
}

当我的代码到达 initPlaylist() 函数时,视频数组似乎为空,我有一种感觉它实际上在 $.getJSON() 调用之前被触发... 这可能吗?如果我在每个 push() 之后添加一个 console.log(视频),则实际上正在构建数组。

最佳答案

$.each(similars.artist, function(c, artist) {
// doing ajax stuff here
$.getJSON('url', function(data) {
// this will get called later
$.each(data.feed.entry, function(i,video) {
videos.push({
id: video.id.$t.split(":")[3],
title: video.title.$t
});
});
});
});
// trying to manipulate ajax data now :(
initPlaylist();

您的视频是空的,因为您试图在它准备好之前对其进行操作。

你想要做的是使用 jQuery 1.5+ 延迟对象

var ajaxs = $.map(similars.artist, function(artist, c) {
return $.getJSON('url', function(data) {
$.each(data.feed.entry, function(i,video) {
videos.push({
id: video.id.$t.split(":")[3],
title: video.title.$t
});
});
});
});
// when all the ajaxs finish then call init play list
$.when.apply($, ajaxs).then(initPlaylist);

关于javascript - 为什么我的数组在JS中建好数组后调用函数时显示为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6127004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com