在JavaScript中声明多个变量 [英] Declare multiple variables in JavaScript

查看:69
本文介绍了在JavaScript中声明多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是正确的方法吗?

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


推荐答案

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

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
[]

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

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.

这篇关于在JavaScript中声明多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆