bob 2
bob 2

Reputation: 185

Initializing a javascript array

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;

Upvotes: 14

Views: 33263

Answers (5)

Mr. Goferito
Mr. Goferito

Reputation: 7001

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

Upvotes: 1

brymck
brymck

Reputation: 7663

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

Upvotes: 17

David G
David G

Reputation: 96790

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

Upvotes: 1

user113716
user113716

Reputation: 322452

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.

Upvotes: 13

stewe
stewe

Reputation: 42612

var counter={A:0,B:0,C:0,D:0,E:0,F:0,G:0};

Upvotes: 1

Related Questions