13

Is there another (more beautiful) way to initialize this Javascript array?

    var counter = [];
    counter["A"] = 0; 
    counter["B"] = 0;
    counter["C"] = 0;
    counter["D"] = 0;
    counter["E"] = 0;
    counter["F"] = 0;
    counter["G"] = 0;
Jared Farrish
  • 47,157
  • 17
  • 93
  • 101
bob 2
  • 175
  • 1
  • 1
  • 8

5 Answers5

17

A. That doesn't work, or at least not the way you'd hope it to. You initialized an array when what you're most likely looking for is a hash. counter will still return [] and have a length of 0 unless you change the first line to counter = {};. The properties will exist, but it's a confusing use of [] to store key-value pairs.

B:

var counter = {A: 0, B: 0, C: 0, D: 0, E: 0, F: 0, G: 0};
brymck
  • 7,424
  • 26
  • 30
  • -1 because just about everything stated above is wrong. It does "work", the properties are assigned. By "counter will still return 0" presumably you mean `counter.toString()`, but that will return an empty string (per EMCA-262 §15.4.4.2 since *counter* has no numeric properties). If *counter* is initialised as an object, then `counter.toString()` will not return "0", it will return `[object Object]` per ECMA-262 §15.2.4.2. – RobG Aug 11 '11 at 00:35
  • 1
    Actually it was dumber: running his code in the console gave me `0` because the last line was `counter["G"] = 0;`. I was referring to the console output, in any case. You are right about being able to assign almost anything as a property to an object, of course, so I reworded that portion to point out the desirability of using `{}` over `[]` as an associative array, if for no other reason than least surprise. – brymck Aug 11 '11 at 01:02
13

Use an object literal instead of an array, like this:

var counter = {A:0,B:0,C:0}; // and so on

Then access the properties with dot notation:

counter.A;  // 0

...or square bracket notation:

counter['A'];  // 0

You'll primarily use Arrays for numeric properties, though it is possible to add non-numeric properties as you were.

user113716
  • 310,407
  • 61
  • 442
  • 435
1
var counter={A:0,B:0,C:0,D:0,E:0,F:0,G:0};
stewe
  • 40,424
  • 13
  • 77
  • 74
1

It would make more sense to use an object for this:

    var counter = {
        A: 0, 
        B: 0, 
        C: 0, 
        D: 0, 
        E: 0, 
        F: 0, 
        G: 0
     };
David G
  • 90,891
  • 40
  • 158
  • 247
0

If you really wanted an array full of zeroes, Array(5).fill(0) would do the trick.

Mr. Goferito
  • 5,393
  • 3
  • 23
  • 26