在if语句中定义JavaScript变量 [英] Defining JavaScript variables inside if-statements

查看:1160
本文介绍了在if语句中定义JavaScript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is defining JavaScript variables inside if-statements correct?

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

我知道上面的代码可行,但WebMatrix会突出显示变量。

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

我应该在if语句之外定义变量吗?或者第一个选项是正确的?或者它真的没关系?

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

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


推荐答案

截至正式发布ES2017规范(2017-07-08),EcmaScript 确实现在使用 let const 关键字。

As of the official release of ES2017 spec (2017-07-08), EcmaScript does support true block scope now using the let or const keywords.

由于ECMAscript没有块范围,但函数范围,在函数上下文中声明任何变量是一个非常好的主意。

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

即使你可以在函数上下文中的任何一点创建变量和函数声明,如果你没有完全意识到后果,它会引起一些奇怪的麻烦。

Even though you can make 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.

头痛例如:

var foo = 10;

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

猜猜看,我们得到了什么? '在此处调用 myfunc 时发出警报。这是因为ECMAscript解释器将 var 语句和函数声明自动提升到上下文的顶部。基本上, foo 在第一个 if语句 undefined >。

Guess what, we're getting a 'wut?' alert when calling myfunc here. That is because an ECMAscript interpreter will hoist any var statement and function declaration to the top of the context automatically. Basically, foo gets initialized to undefined before the first if statement.

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

这篇关于在if语句中定义JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆