1

In order to clear up my code I have been paying attention to all of the hints in Web Storm. The following duplicate declaration errors have confused me.

In the following code, is the double use of var necessary (or advised) to prevent a global variable? (or could I remove the second var in from of s:

function run(x) {
    if(x == 5) {
        var s = 'Yes',
            bar = 1,
            baz = 2
    } else {
        var s = 'No',
            bar = 1,
            baz = 2
    }
    console.log(s);
}

Also, if I do remove var in the else condition, I get a comma expression error, indicating that my code may be "overly clever".

Writing

else {
    bar = 1,
    baz = 2
 }

Seems to me to be bad syntax

4

2 に答える 2

3

これには、次を使用します。

function run(x) {
  var s = (x === 5) ? 'Yes' : 'No';
  var bar = 1;
  var baz = 2;

  console.log(s);
}

変数が同じスコープにあるため、現在重複宣言エラーが発生しています。

于 2014-06-19T10:59:43.680 に答える
1

元のコードに固執する場合、最もクリーンな解決策は次のとおりです。

function run(x) {
    var s, bar, baz;

    if(x == 5) {
        s = 'Yes';
        bar = 1;
        baz = 2;
    } else {
        s = 'No';
        bar = 1;
        baz = 2;
    }
    console.log(s);
}
于 2014-06-19T11:08:13.640 に答える