变量在运行时未定义,但在使用调试器时得到定义

Variable is undefined in runtime, but gets defined when using debugger

我是 javascript 新手,正在 javascript 中尝试此代码(使用 jQuery):

$(document).ready(function() {
var nodes=[];
$.getJSON('/get/data', function(data) {
            nodes.push(data);
        });
//debugger
console.log(nodes);
console.log(nodes[0]);
});

这是我在控制台中看到的:

[ ]
undefined

但是当我取消注释 //debugger 和 运行 它时,我得到这些结果:

  []
  []
  []
 [[Object { id=10,  label="foo"}, Object { id=9,  label="bar"}, 43 more...]]
 [Object { id=10,  label="foo"}, Object { id=9,  label="bar"}, ...]

这是怎么回事?我不明白激活调试器会如何影响变量并使其定义或未定义。顺便说一下,这只是一个更大的脚本的一部分,所以它可能是一个因素。

这是一个 异步 函数,因此 nodes 在您的回调获得 运行 之前不会被填充。试试这个:

var nodes=[];
 //this "function(data)" is a callback to be executed when you get your data back
 $.getJSON('/get/data', function(data) {
     nodes.push(data);
     console.log(nodes); //<--this now has data!
     console.log(nodes[0]);
});