Declaring multiple variables in JavaScript

后端 未结 17 782
时光说笑
时光说笑 2020-11-22 13:16

In JavaScript, it is possible to declare multiple variables like this:

var variable1 = "Hello, World!";
var variable2 = "Testing...";
var          


        
17条回答
  •  死守一世寂寞
    2020-11-22 13:43

    My only, yet essential, use for a comma is in a for loop:

    for (var i = 0, n = a.length; i < n; i++) {
      var e = a[i];
      console.log(e);
    }
    

    I went here to look up whether this is OK in JavaScript.

    Even seeing it work, a question remained whether n is local to the function.

    This verifies n is local:

    a = [3, 5, 7, 11];
    (function l () { for (var i = 0, n = a.length; i < n; i++) {
      var e = a[i];
      console.log(e);
    }}) ();
    console.log(typeof n == "undefined" ?
      "as expected, n was local" : "oops, n was global");
    

    For a moment I wasn't sure, switching between languages.

提交回复
热议问题