Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  112] [ 1]  / answers: 1 / hits: 46783  / 14 Years ago, tue, november 2, 2010, 12:00:00

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

More From » variables

 Answers
20

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.


[#95102] Saturday, October 30, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;