javascript 为什么 Jshint 在这个 if 语句中说“变量已经定义”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19412727/
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
Why is Jshint saying "variable already defined" in this if statement?
提问by user2413333
I have this code:
我有这个代码:
if ( something is true ) {
var someVar = true;
} else {
var someVar = false;
}
JsHint is saying that "someVar was already defined" on the else statement part. Why is this and how do I fix it?
JsHint 在 else 语句部分说“已经定义了 someVar”。这是为什么,我该如何解决?
Thanks
谢谢
回答by Alnitak
JS variables do not have block scope, they have "function" scope (or sometimes global).
JS 变量没有块作用域,它们有“函数”作用域(或者有时是全局的)。
The declaration (but not the assignment) is "hoisted" to the top of the function.
声明(但不是赋值)被“提升”到函数的顶部。
jshint is warning you that you have two such declarations - your code is equivalent to:
jshint 警告您,您有两个这样的声明 - 您的代码等效于:
var someVar;
var someVar; // warning!
if (something) {
someVar = true;
} else {
someVar = false;
}
回答by Erik Christianson
This is due to hoisting.
这是由于吊装。
In javascript, no matter where you define a new variable with var
, it moves it to the top of the function you are in. Your code is producing the following above your if block at the top of the function:
在 javascript 中,无论您在哪里定义一个新变量var
,它都会将其移动到您所在函数的顶部。您的代码在函数顶部的 if 块上方生成以下内容:
var someVar;
var someVar;
Here is a tutorial to explain hoisting:
这是一个解释提升的教程:
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/
回答by Pointy
You shouldn't put var
declarations in such places. Put the var
declaration before the if
, and then just set "someVar" to a value.
你不应该把var
声明放在这样的地方。将var
声明放在之前if
,然后只需将“someVar”设置为一个值。
Indeed, here you don't need an if
statement at all:
事实上,在这里你根本不需要if
声明:
var someVar = !!(something);
will do the same thing. (The double application of !
ensures that "someVar" is set to either true
or false
, based on the "truthiness" of something
.)
会做同样的事情。(基于 的“真实性”,的双重应用!
确保“someVar”设置为true
或。)false
something