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;
To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.
JavaScript Arrays - How to Create an Array in JavaScript. An array is a type of data structure where you can store an ordered list of elements. In this article, I will show you 3 ways you can create an array using JavaScript. I will also show you how to create an array from a string using the split() method.
Using the fill() method The fill() method, fills the elements of an array with a static value from the specified start position to the specified end position. If no start or end positions are specified, the whole array is filled. One thing to keep in mind is that this method modifies the original/given array.
The process of assigning values to the array elements is called array initialization. Once an array is declared, its elements must be initialized before they can be used in the program. If they are not properly initialized the program produces unexpected results.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With