初始化一个 javascript 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7019394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initializing a javascript array
提问by bob 2
Is there another (more beautiful) way to initialize this Javascript array?
有没有另一种(更漂亮的)方法来初始化这个 Javascript 数组?
var counter = [];
counter["A"] = 0;
counter["B"] = 0;
counter["C"] = 0;
counter["D"] = 0;
counter["E"] = 0;
counter["F"] = 0;
counter["G"] = 0;
回答by brymck
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.
答:那行不通,或者至少不是您希望的那样。当您最有可能寻找的是散列时,您初始化了一个数组。counter
仍然会返回[]
,并有一个长度0
,除非你改变了第一线counter = {};
。属性将存在,但[]
用于存储键值对是一种令人困惑的用法。
B:
乙:
var counter = {A: 0, B: 0, C: 0, D: 0, E: 0, F: 0, G: 0};
回答by user113716
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.
您将主要将数组用于数字属性,但也可以像以前一样添加非数字属性。
回答by stewe
var counter={A:0,B:0,C:0,D:0,E:0,F:0,G:0};
回答by 0x499602D2
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
};
回答by Mr. Goferito
If you really wanted an array full of zeroes, Array(5).fill(0)
would do the trick.
如果你真的想要一个充满零的数组,Array(5).fill(0)
那就可以了。