forEach 循环内的 JavaScript 变量范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33154718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:10:41  来源:igfitidea点击:

JavaScript variable scope inside forEach loop

javascriptscope

提问by irom

In the code below there is callback function used with forEach loop going over returned results. Is variable 'error' inside forEach loop and 'error' in callback same variables ?

在下面的代码中,有一个回调函数用于 forEach 循环遍历返回的结果。forEach 循环中的变量 'error' 和回调中的变量'error' 是否相同?

session.getAll(options, function (error, varbinds) {
    varbinds.forEach(function (vb) {
        if (error) 
            console.log('getALL Fail ');
        else              
            console.log(vb.value);            
    });
});

回答by BCDeWitt

Yes, it is the same variable.

是的,它是同一个变量。

I'm not sure how much you know. So, I'm going to explain in detail. Scoping in JavaScript is at the function level*. Think of function definitions as points on a tree. Each point on the tree is a scope. When using a variable, you can only use what is at your current scope and anything available to ancestors going up to the top (global scope). Here are a few rules & examples that may help you better understand:

我不确定你知道多少。所以,我要详细解释一下。JavaScript 中的作用域是在函数级别*。将函数定义视为树上的点。树上的每个点都是一个范围。使用变量时,您只能使用当前范围内的内容以及向上到顶部(全局范围)的祖先可用的任何内容。以下是一些规则和示例,可以帮助您更好地理解:

*UPDATE: ES6 constand letare block-level

*更新:ES6constlet块级

Inner functions have access to outer function-level variables

内部函数可以访问外部函数级变量

function a() {
    var a = 4;

    function b() {
        alert(a); /* a = 4 */
    }
}

Parameters are defined at the same scope as if they were defined one line below

参数在相同的范围内定义,就好像它们在下面一行定义一样

function a(a) {
    // variable "a" is at same scope as the example above

    function b() {
        alert(a);
    }
}

Variables in adjacent functions are not accessible

相邻函数中的变量不可访问

Function a() is the parent. b() and c() are its children. Those children cannot access each other's variables.

函数 a() 是父函数。b() 和 c() 是它的孩子。这些孩子不能访问彼此的变量。

function a() {

    function b() {
        var aValue = 2;
    }

    function c() {
        alert(aValue); /* "aValue" is undefined here */
    }
}

Location of function definition is what counts

函数定义的位置很重要

This returns 5 if you run main();:

如果您运行,这将返回 5 main();

function getValue(returnFunc) {
    var a = 7;
    alert(returnFunc());
}

function main() {
    var a = 5;
    getValue(function() { return a; }); // anonymous function becomes "returnFunc"
}

Lastly, variable overriding

最后,变量覆盖

(function getValue() {
    var a = 5;

    (function () {
        var a = 7;
        alert(a);
    })();

    alert(a);
})();

I tried to avoid using self-invoking functions/IIFEs for these examples but I just couldn't help myself on this last one. It's the easiest way, I think. Run this and you'll get 7, then 5. But, if you exclude "var" on that inner "a"...

我试图避免在这些示例中使用自调用函数/IIFE,但在最后一个中我无法自拔。我认为这是最简单的方法。运行这个,你会得到 7,然后是 5。但是,如果你在那个内部的“a”上排除“var”......

(function getValue() {
    var a = 5;

    (function () {
        a = 7;
        alert(a);
    })();

    alert(a);
})();

You'll get 7, 7. This is because "var" creates a new space in memory. Also, if there is a name conflict with something in a higher scope, it gets overridden as a different variable (despite having the same name).

你会得到 7, 7。这是因为“var”在内存中创建了一个新空间。此外,如果名称与更高范围内的某些内容发生冲突,它会被覆盖为不同的变量(尽管名称相同)。

For some more examples, please see: What is the scope of variables in JavaScript?

有关更多示例,请参阅:JavaScript 中变量的作用域是什么?

回答by taxicala

Yes, it's the same variable, it would change if you define another errorvariable inside the scope of the forEach callback by using the varkeyword:

是的,它是同一个变量,如果你error使用var关键字在 forEach 回调的范围内定义另一个变量,它会改变:

session.getAll(options, function (error, varbinds) {
    varbinds.forEach(function (vb) {
        if (error) //Same error as the error parameter above
            console.log('getALL Fail ');
        else              
            console.log(vb.value);            
    });
});

session.getAll(options, function (error, varbinds) {
    varbinds.forEach(function (vb) {
        var error = false; //New error for this closure.
        if (error) 
            console.log('getALL Fail ');
        else              
            console.log(vb.value);            
    });
});