开发者

Initializing a javascript array

开发者 https://www.devze.com 2023-03-27 11:04 出处:网络
Is there another (more beautiful) way to initialize this Javascript array? var counter = [];开发者_开发技巧

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消