在 if 语句中定义 JavaScript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11532072/
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-08-24 06:12:14  来源:igfitidea点击:

Defining JavaScript variables inside if-statements

javascriptvariablesif-statement

提问by lukeshek

Is defining JavaScript variables inside if-statements correct?

在 if 语句中定义 JavaScript 变量是否正确?

if(a==1){
    var b = 1;
} else {
    var b = 0;
}

I know the code above will work, however, WebMatrix highlights the variables.

我知道上面的代码会起作用,但是,WebMatrix 突出显示了变量。

Should I define the variables outside the if-statement? Or the first option's correct? Or it doesn't really matter?

我应该在 if 语句之外定义变量吗?还是第一个选项正确?还是真的无所谓?

var b = '';
if(a==1){
    b = 1;
} else {
    b = 0;
}

回答by jAndy

As of the official release of ES2017 spec (2017-07-08), EcmaScript doessupport true block scope now using the letor constkeywords.

作为ES2017规范(2017年7月8日)正式发布的,EcmaScript的确实现在使用支持真正块的范围letconst关键字。



Since ECMAscript doesn't have block scopebut function scope, its a very good idea to declare any variable on the top of your function contexts.

由于 ECMAscript 没有块作用域而是函数作用域,因此在函数上下文的顶部声明任何变量是一个非常好的主意。

Even though you canmake variable and function declarations at any point within a function context, it's very confusing and brings some weird headaches if you aren't fully aware of the consequences.

尽管您可以在函数上下文中的任何时候进行变量和函数声明,但如果您没有完全意识到后果,它会非常混乱并且会带来一些奇怪的头痛。

Headache example:

头痛示例:

var foo = 10;

function myfunc() {
    if (foo > 0) {
        var foo = 0;
        alert('foo was greater than 0');
    } else {
        alert('wut?');
    }
}

Guess what, we're getting a 'wut?' alert when calling myfunchere. That is because an ECMAscript interpreter will hoistany varstatement and function declarationto the top of the context automatically. Basically, foogets initialized to undefinedbefore the first if statement.

猜猜怎么着,我们得到了一个'wut?在myfunc这里打电话时提醒。这是因为 ECMAscript 解释器会自动将任何语句和函数声明提升到上下文的顶部。基本上,被初始化为前第一。varfooundefinedif statement

Further reading: JavaScript Scoping and Hoisting

进一步阅读:JavaScript 范围和提升

回答by farhadf

Note that ECMAscript 6 does support block-level variables using the 'let' rather than the 'var' keyword. While variables declared with 'var' are hoisted to be function-scope regardless of where they are declared, those defined using 'let' are scoped to the enclosing block only.

请注意,ECMAscript 6 确实支持使用“let”而不是“var”关键字的块级变量。虽然用 'var' 声明的变量无论在何处声明都被提升为函数作用域,但使用 'let' 定义的变量仅作用于封闭块。

回答by farhadf

Putting a var inside an if statement is not against "the rules" of the language, but it means that, because of var hoisting, that var will be defined regardless of whether the if statement's condition is satisfied.

将 var 放在 if 语句中并不违反语言的“规则”,但这意味着,由于 var 提升,无论 if 语句的条件是否满足,都会定义该 var。

回答by Neil

Because JavaScript's variables have function-level scope, your first example is effectively redeclaring your variable, which may explain why it is getting highlighted.

因为 JavaScript 的变量具有函数级作用域,所以您的第一个示例有效地重新声明了您的变量,这可以解释为什么它会被突出显示。

On old versions of Firefox, its strict JavaScript mode used to warn about this redeclaration, however one of its developers complained that it cramped his style so the warning was turned off. (Current versions of Firefox support a block-level variable declaration syntax.)

在旧版本的 Firefox 上,其严格的 JavaScript 模式用于警告此重新声明,但其中一位开发人员抱怨说它限制了他的风格,因此警告被关闭。(当前版本的 Firefox 支持块级变量声明语法。)

回答by hcarver

See function fouron What is the scope of variables in JavaScript?

见功能four有什么是JavaScript中变量的作用域?

As of 2012, there's no block-level scope in JavaScript. So your first version is fine: the variables are defined in the scope outside the ifblock.

截至 2012 年,JavaScript 中没有块级作用域。所以你的第一个版本很好:变量在if块外的范围内定义。