在JavaScript中声明多个变量

FFi*_*ish 38 javascript variables declare

我想在函数中声明多个变量:

function foo() {
    var src_arr     = new Array();
    var caption_arr = new Array();
    var fav_arr     = new Array();
    var hidden_arr  = new Array();
}
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

var src_arr = caption_arr = fav_arr = hidden_arr = new Array();
Run Code Online (Sandbox Code Playgroud)

med*_*iev 74

是的,如果你希望它们都指向内存中的同一个对象,那么很可能你希望它们是单独的数组,这样如果一个变异,其他的就不会受到影响.

如果您不希望它们都指向同一个对象,请执行此操作

var one = [], two = [];
Run Code Online (Sandbox Code Playgroud)

[]是一个用于创建数组的简写文字.

这是一个控制台日志,它指出了不同之处:

>> one = two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[1]
>> one = [], two = [];
[]
>> one.push(1)
1
>> one
[1]
>> two
[]
Run Code Online (Sandbox Code Playgroud)

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


CMS*_*CMS 18

即使您希望所有变量都指向同一个对象,也请远离该分配模式.

实际上,只有第一个是变量声明,其余的只是可能未声明的标识符的赋值!

将值分配给一个未声明的标识符(又名未申报分配)是强烈反对,因为,如果标识符未在作用域链发现,一个全局变量将被创建.例如:

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"
Run Code Online (Sandbox Code Playgroud)

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

相比之下,如果写得正确,我们会看到以下内容:

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"
Run Code Online (Sandbox Code Playgroud)