简体   繁体   中英

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;

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

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.

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

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

如果你真的想要一个充满零的数组,那么Array(5).fill(0)就可以了。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM