Javascript 数组作用域 - 这里是新手
所以,我一边学习 Javascript,一边玩白色的 Google Calendar API,我只是不明白这段代码是如何工作的:
var entriesResult = [];
var data = new Date(2010,3,22,17,0,0);
var callback = function(result) {
var entries = result.feed.getEntries();
if (entries.length != 0) {
entriesResult = eventsManager(entries, 0, data);
window.alert("inner entriesResult " + entriesResult.length);
}
}
this.service.getEventsFeed(this.query, callback, handleGDError);
window.alert("outer entriesResult " + entriesResult.length);
eventsManager() 是一个返回对象数组的函数。
getEventsFeed() 它是一个 API 函数:它查询服务并将“提要根”(包含所选项目的提要)传递给回调函数。
为什么第一个警报(内部..)输出有效的entriesResult.length,而第二个警报(外部..)始终输出0?
我认为 javascript 数组总是通过引用传递,我的代码有什么问题吗? 谢谢 :)
So, I am learning Javascript while playing white Google Calendar APIs and I just can't figure how this piece of code is working this way:
var entriesResult = [];
var data = new Date(2010,3,22,17,0,0);
var callback = function(result) {
var entries = result.feed.getEntries();
if (entries.length != 0) {
entriesResult = eventsManager(entries, 0, data);
window.alert("inner entriesResult " + entriesResult.length);
}
}
this.service.getEventsFeed(this.query, callback, handleGDError);
window.alert("outer entriesResult " + entriesResult.length);
eventsManager() is a function that returns an array of Objects.
getEventsFeed() it's an API function: it queries the service and pass a "feed root" (a feed with selected items) to the callback function.
Why the first alert (inner..) outputs a valid entriesResult.length while the second one (outer..) always outputs a 0?
I tought javascript arrays are always passed by reference, what's wrong whit my code?
Thank you :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getEventsFeed
函数进行异步 AJAX 调用,并在服务器回复时调用callback
。换句话说,回调函数在其余代码之后运行一段时间。因此,当数组仍为空时,外部
alert
在回调之前执行。编辑
要从 AJAX 调用返回值,您需要接受回调作为参数,然后在有要返回的值后调用回调。
例如:
您可以像调用
getEventsFeed
一样调用此函数。例如:
The
getEventsFeed
function makes an asynchronous AJAX call and callscallback
when the server replies. In other words, the callback function is run some time after the rest of the code.Therefore, the outer
alert
is executed before the callback, when the array is still empty.EDIT
To return a value from an AJAX call, you need to accept a callback as a parameter, then call the callback once you have a value to return.
For example:
You would call this function the same way you call
getEventsFeed
.For example:
该行:
在启动异步操作后(完成之前)立即执行。
回调函数中的行稍后在异步操作完成后执行。
The line:
is executed immediately after you start the async operation (before it completes).
the line in the callback function is executed later, after the async operation is complete.