English 中文(简体)
JavaScript 对象中的范围问题
原标题:Scope Issues In JavaScript Object

我正试图在我的 JavaScript 对象中创建一个数组, 其中包含从 JSON 文件里用 $.getJSON () 函数在 jQuery 中提取的物体。 我正运行到范围问题, 在那里, 数组元素似乎被设置在 $.getJSON () 函数中, 但是在它之外, 数组是空的 。 以下是代码 :

function player(playlist){
...
var tracks = [];

this.start = function() {
...
    $.getJSON(playlist, function(data){
        $.each(data.tracks, function(key,value){
            var track_info = function(info){return info}(value);
            tracks.push(track_info);
        });
        console.log("from .getJSON function");
        console.log(tracks);
    });
    console.log("outside .getJSON function");
    console.log(tracks);
    ...
};
...
$(document).ready(function(){
    var the_player = new player(playlist);
    the_player.start();
)};

产出是:

outside .getJSON function
[]
from .getJSON function
[Object, Object, Object]

所有对象都包含JSON文件的正确数据。

我对此感到困惑, 有人能帮我理解吗?

最佳回答

提示是顺序 :

outside .getJSON function
[]

随 随 随 随

from .getJSON function
[Object, Object, Object]

您在得到 JSON 响应前正在执行您的外部代码, 这并不奇怪, tracks 是空的。 这看起来似乎是反直观的 - < code> from. getJSON 函数 出现在源头, 但正在执行第二个! 这是因为 < code>. getJSON 不是同步的 。 它在继续下一个语句前没有执行回调参数 。 它会立即延续到下一个语句, 稍后再执行回调 。

问题回答

$.getJSson 是一个 AJAX 的电话, 并且非常同步。 这意味着您 connoole.log ("在.getJSson 函数" 外) ; 在您 AJAX 调回( 并填充数组) 之前被调用 。 提示是, 正在发生的是您在内部之前看到的输出 。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.