This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
                            
                                (6个答案)
                            
                    
                5年前关闭。
        

    

我是一个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]);
});

关于javascript - 变量在运行时中未定义,但在使用调试器时会被定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29403535/

10-11 22:17
查看更多