为什么Jshint说“变量已定义”?在这个if语句? [英] Why is Jshint saying "variable already defined" in this if statement?

查看:116
本文介绍了为什么Jshint说“变量已定义”?在这个if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

 if ( something is true ) {
        var someVar = true;
    } else {
       var someVar = false;
    }

JsHint在else语句部分说someVar已定义。为什么会这样,我该如何解决呢?

JsHint is saying that "someVar was already defined" on the else statement part. Why is this and how do I fix it?

谢谢

推荐答案

JS变量没有块范围,它们具有功能范围(或者有时是全局)。

JS variables do not have block scope, they have "function" scope (or sometimes global).

声明(但不是赋值)被提升到函数的顶部。

The declaration (but not the assignment) is "hoisted" to the top of the function.

jshint警告你有两个这样的声明 - 你的代码相当于:

jshint is warning you that you have two such declarations - your code is equivalent to:

var someVar;
var someVar;  // warning!
if (something) {
     someVar = true;
} else {
     someVar = false;
}

这篇关于为什么Jshint说“变量已定义”?在这个if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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