我在javascript中做简单的应用程序。我有" main_script"在哪里我调用一切。有全局变量" feed"这是一个数组,如下所示:
var feeds = [];
然后我使用函数,从多个URL(也是数组)加载JSON文件:
feeds = LoadJsonFeeds(urls); // Load feeds
console.log("main_code feeds.length: " + feeds.length);
我稍后提到的控制台日志。好的,现在他是我的LoadJsonFeeds(在不同的.js文件中,只是一个函数):
function LoadJsonFeeds(urls) {
var feeds_tmp = [];
// URLs can be more - for example 50 feeds from url[0] and 20 from url[1]
for(var u = 0; u < url.length; u++) {
$.getJSON(url[u], function(data) {
var allFeeds = data.Result.Items; // allFeeds without check if they are ok
for(var i = 0; i < allFeeds.length; i++) {
// Is feed ok?
if (allFeeds[i].Text != null)
{
// Some more checking, but lets say ok for this
feeds_tmp.push(allFeeds[i]);
}
// This I mention later
console.log("LoadJson feeds.length: " + feeds.length);
}
});
}
console.log("LoadJson return"); // Mention later
return feeds_tmp;
}
这是我正在努力解决的问题。当我看到控制台时,我看到了这一点:
LoadJson return
main_code feeds.length: 0
LoadJson feeds.length: 1
LoadJson feeds.length: 2
LoadJson feeds.length: 3
etc...
我只是没有看到它背后的逻辑!它怎么能首先返回函数,然后main_script继续。之后,函数ALTER逐个全局变量&#34; feeds&#34;。我怀疑匿名功能,但不知道如何处理它。
我想要实现的目标是什么?很简单,我想拥有从URL加载JSON文件的功能。例如,url [0]有50个feed,url [1]有20个。如果一切正常,那么它应该返回70个feed的数组。我在main_script中第一次使用它,然后在更新的间隔中使用它,我每隔几秒就调用一次。在这个函数中,我检查哪个feed是新的并把它放在其他地方:
function UpdateFeeds(url) {
console.log("updating...");
var feeds_tmp = LoadJsonFeeds(url);
console.log("Update feeds_tmp.length: " + feeds_tmp.length); // This is 0
for(var f_tmp = 0; f_tmp < feeds_tmp.length; f_tmp++) { // This does not happen because feeds_tmp.length = 0
for(var f = 0; f < feeds.length; f++) {
// Check what feed is new and put it somewhere else (the new one)
}
}
}
feeds = feeds_tmp; // Make all new feeds the global variable
}
但是由于返回的数组为0,因此不会发生forloop。但它仍然会改变全球变量&#34; feed&#34;无论如何。对于主要功能而言无关紧要。在全局变量中,数据位于其中,但我确实需要找到一个新数据并使用它进行一些工作。但由于它不起作用,我很遗憾。
我错过了什么以及如何解决这个问题?谢谢!
答案 0 :(得分:1)
您的console.log("LoadJson feeds.length: " + feeds.length);
稍后调用,因为它是异步调用,您可以将此函数更新为
function LoadJsonFeeds(urls,callback) {
var feeds_tmp = [];
// URLs can be more - for example 50 feeds from url[0] and 20 from url[1]
for(var u = 0; u < url.length; u++) {
$.getJSON(url[u], function(data) {
var allFeeds = data.Result.Items; // allFeeds without check if they are ok
for(var i = 0; i < allFeeds.length; i++) {
// Is feed ok?
if (allFeeds[i].Text != null)
{
// Some more checking, but lets say ok for this
feeds_tmp.push(allFeeds[i]);
}
// This I mention later
console.log("LoadJson feeds.length: " + feeds.length);
}
if(u==url.length.1) // to make sure all URL loaded
callback(feeds_tmp)
});
}
}
将您的功能称为
feeds = LoadJsonFeeds(urls,function(feeds){
console.log("main_code feeds.length: " + feeds.length);
}); // Load feeds