本文介绍了在同一范围内声明两次Javascript变量 - 这是一个问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是否会导致任何问题?:

Would the following code cause any issues?:

var a = 1;
var a = 2;

我的理解是javascript变量是在范围的开头声明的。例如:

My understanding is that javascript variables are declared at the start of the scope. For example:

var foo = 'a';
foo = 'b';
var bar = 'c';

处理为:

var foo;
var bar;
foo = 'a';
foo = 'b';
bar = 'c';

因此,我的初始代码段将成为:

Therefore would my initial code snippet become:

var a;
a = 1;
a = 2;

或者它会变成:

var a;
var a;
a = 1;
a = 2;

我知道在同一范围内两次声明一个javascript变量不是好习惯,但我'我对这样做的影响更感兴趣。

I understand that declaring a javascript variable twice in the same scope isn't good practice, but I'm more interested in the impact of doing this.

推荐答案

正如你所说,两次以上的同一个var,JavaScript会移动声明到范围的顶部然后你的代码会变成这样:

As you said, by twice of more the same var, JavaScript moves that declaration to the top of the scope and then your code would become like this:

var a;
a = 1;
a = 2;

因此,它不会给我们任何错误。

Therefore, it doesn't give us any error.

循环的同样的行为(它们的标题中没有本地范围),所以下面的代码非常常见:

This same behaviour occurs to for loops (they doesn't have a local scope in their headers), so the code below is really common:

for (var i = 0; i < n; i++) {
    // ...
}
for (var i = 0; i < m; i++) {
    // ...
}

这就是为什么像这样的JavaScript大师建议程序员手动将这些声明移到顶端范围:

That's why JavaScript gurus like Douglas Crockford suggest programmers to manually move those declarations to the top of the scope:

var i;    // declare here
for (i = 0; i < n; i++) {    // initialize here...
    // ...
}
for (i = 0; i < m; i++) {    // ... and here
    // ...
}

这篇关于在同一范围内声明两次Javascript变量 - 这是一个问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 01:09