在 JavaScript 中声明多个变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4082560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:31:06  来源:igfitidea点击:

Declare multiple variables in JavaScript

javascriptvariablesdeclare

提问by FFish

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();

回答by meder omuraliev

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.

是的,如果您希望它们都指向 memory 中的同一个对象,但很可能您希望它们是单独的数组,以便如果一个数组发生变异,则其他数组不受影响。

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 oneand twoto point to the same object/array in memory. If I use the .pushmethod it pushes 1 to the array, and so both oneand twohave 1inside. In the second since I defined unique arrays per variable so when I pushed to one, two was unaffected.

在第一部分中,我定义onetwo指向内存中的同一个对象/数组。如果我使用.push它推动1到阵列的方法,以及因此两个onetwo具有1内部。第二次,因为我为每个变量定义了唯一的数组,所以当我推到一个时,两个不受影响。

回答by CMS

Please stay awayfrom 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:

强烈建议不要为未声明的标识符(又名未声明的赋值赋值,因为如果在作用域链中找不到该标识符,则会创建一个 GLOBAL 变量。例如:

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 TypeErrorexception, to prevent implied globals.

此外,ECMAScript 5th Strict Mode 不允许这种赋值。在严格模式下,对未声明的标识符进行的分配将导致TypeError异常,以防止隐含的全局变量。

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"

回答by hvgotcodes

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

不,您的第二个语句将创建对同一个数组的四个引用。你要:

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

回答by heximal

All those variables will refer to one Array object.

所有这些变量都将引用一个 Array 对象。

回答by ambianBeing

For all intents and purposes the literal []notation syntaxshould be used. Since the Array constructoris ambiguous in how it deals with its parameters.

出于所有意图和目的,应使用符号语法。由于Array 构造函数在如何处理其参数方面不明确。literal []

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 Arrayof passed lengthof empty slots with undefinedvalues.

如果传递给 Array 构造函数的唯一参数是 0 到 232-1(含)之间的整数,则返回一个新的 JavaScript 数组,其长度属性设置为该数字。这意味着带有值的空槽Array传递长度undefined

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 assignmentwhich 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();