Declare multiple variables in JavaScript

老子叫甜甜 提交于 2019-12-20 16:13:53

问题


I want to declare multiple variables in a function:

function foo() {
    var src_arr     = new Array();
    var caption_arr = new Array();
    var fav_arr     = new Array();
    var hidden_arr  = new Array();
}

Is this the correct way to do this?

var src_arr = caption_arr = fav_arr = hidden_arr = new Array();

回答1:


Yes, it is if you want them all to point to the same object in memory, but most likely you want them to be individual arrays so that if one mutates, the others are not affected.

If you do not want them all to point to the same object, do

var one = [], two = [];

The [] is a shorthand literal for creating an array.

Here's a console log which indicates the difference:

>> one = two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[1]
>> one = [], two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[]

In the first portion, I defined one and two to point to the same object/array in memory. If I use the .push method it pushes 1 to the array, and so both one and two have 1 inside. In the second since I defined unique arrays per variable so when I pushed to one, two was unaffected.




回答2:


Please stay away from that assignment pattern, even if you wanted to have all variables pointing to the same object.

In fact, only the first one will be a variable declaration, the rest are just assignments to possibly undeclared identifiers!

Assigning a value to an undeclared identifier (aka undeclared assignment) is strongly discouraged because, if the identifier is not found on the scope chain, a GLOBAL variable will be created. For example:

function test() {
    // We intend these to be local variables of 'test'.
    var foo = bar = baz = xxx = 5;
    typeof foo; // "number", while inside 'test'.
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined", As desired, but,
typeof bar; // "number", BAD!, leaked to the global scope.
typeof baz; // "number"
typeof xxx; // "number"

Moreover, the ECMAScript 5th Strict Mode, disallows this kind of assignments. Under strict mode an assignment made to a non-declared identifier will cause a TypeError exception, to prevent implied globals.

By contrast, here is what we see if written correctly:

function test() {
    // We correctly declare these to be local variables inside 'test'.
    var foo, bar, baz, xxx;
    foo = bar = baz = xxx = 5;
}
test();

// Testing in the global scope. test's variables no longer exist.
typeof foo; // "undefined"
typeof bar; // "undefined"
typeof baz; // "undefined"
typeof xxx; // "undefined"



回答3:


No, your second statement will create four references to the same array. You want:

var src_arr     = [],
    caption_arr = [],
    fav_arr     = [],
    hidden_arr  = [];



回答4:


All those variables will refer to one Array object.




回答5:


For all intents and purposes the literal [] notation syntax should be used. Since the Array constructor is ambiguous in how it deals with its parameters.

From the docs:

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number. And that implies Array of passed length of empty slots with undefined values.

new Array(1, 2, 3); // Result: [1, 2, 3]
new Array(3); // Result: [empty × 3] with undefined at indexes
new Array('3') // Result: ['3']

//this was ambiguous
let x = new Array(5); // Result: [empty × 5]
x.push("Hello"); //expected x as ["Hello", empty, empty, empty, empty]
//Actual x: [empty × 5, "Hello"]

Destructuring syntax:

Another neater way to declare multiple variables is using destructuring assignment which enables unpacking values from arrays, or properties from objects, into distinct variables.

function foo() {
  //destructuring assignment syntax
  let [src_arr, caption_arr, fav_arr, hidden_arr] = [[], [], [], []];

  console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);

  fav_arr.push("fav");
  hidden_arr.push("hidden");

  //After adding some values to couple of arrays
  console.info("Variables::", fav_arr, hidden_arr, caption_arr, src_arr);
}

foo();


来源:https://stackoverflow.com/questions/4082560/declare-multiple-variables-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!