4

With the following code JsLint warns that y is already defined in the 2nd block. I do this fairly often and don't think it is a syntax error since the variable is defined in a different block.

Should I really be using different variable names even though it is in a different block? Is the scope defined by the code block of the if statement or only scoped for a function block?

function x() {
  if (condition1) {
    var y = 0;
    // use y
  }
  if (condition2) {
    var y = 20;
    // use y
  }
}
4

3 回答 3

8

声明一次

function x() {
    var y;
    if (condition1) {
        y = 0;
    }
    if (condition2) {
        y = 20;
    }
}

JS 将来会有块作用域,但它还没有被广泛实施。

于 2013-10-16T17:44:33.717 回答
0

if,for和语句内部没有不同的范围while,但在函数中有。

于 2013-10-16T17:46:05.007 回答
0

我知道已经有公认的答案,但我认为你正在寻找的是一个let声明。

请参阅此答案以了解变量范围(letvs var):https ://stackoverflow.com/a/11444416/3670089

于 2020-05-26T16:14:32.920 回答