简体   繁体   English

嵌套函数中的变量“未定义”

[英]variables in nested functions “undefined”

windows.onload=function(){
    ...somecode...
    var scene = new THREE.Scene();
    ...somecode...
    var i;
    var j;
    for (i=......){...}
    func2();
    function func2(){
        ...somecode...
        BREAK AT THIS LINE;
    }
}

when I break at that line, 当我在那条线上中断时,
firebug says, "i" and "j" is undefined,but an inner function obviously can get the value of "i" right? 萤火虫说,“ i”和“ j”是未定义的,但是内部函数显然可以获得“ i”的值正确吗?
but weirdly, "scene" is showed correctly. 但奇怪的是,“场景”正确显示。
the Ctrl+Shift+I of chrome shows the same thing. chrome的Ctrl + Shift + I表示相同的内容。

but the thing more weird is, when I add 但更奇怪的是,当我添加

alert(i);

to the beginning of func2, 到func2的开始,
this time, the msgBox tells the value of i correctly, 这次,msgBox会正确告诉i的值,
firebug shows the value of i correctly, 萤火虫正确显示i的值,
but j is still showed undefined. 但是j仍然显示为未定义。

I'm wondering why, 我想知道为什么
Both Firebug and chrome shows the same thing so it seems not a bug of Firebug, Firebug和chrome都显示相同的内容,因此似乎不是Firebug的错误,
so is there any hints for this? 所以有什么提示吗?

thanks a lot. 非常感谢。

The value of i should be available in the inner function. i的值应该在内部函数中可用。 This prints "2" in Firebug and node.js as expected: 按预期,这将在Firebug和node.js中输出“ 2”:

(function() { 
     for (var i=0; i<2; ++i) {}; 
     (function() { console.log(i) })(); 
})();

So is it just a matter of the debugger showing incorrect values? 因此,这仅仅是调试器显示错误值的问题吗?

function func2(){
    BREAK HERE;
    ...
    for (var i = ...
    for (var j = ...
}

If you have code like that then those var statements get hoisted to the top of the function declaration so it actually looks like 如果您有这样的代码,则这些var语句将被提升到函数声明的顶部,因此实际上看起来像

function func2() {
    var i, j;
    BREAK HERE:
    ...
    for (i = ...
    for (j = ...
}

Other then that, there is no reason for i and j to be undefined 除此之外,没有理由对ij进行定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM