Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 977
bob 2 Avatar asked Aug 11 '11 00:08

bob 2


People also ask

How do you initialize an array?

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.

What is new array in JavaScript?

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.

How do you load an array in JavaScript?

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.

What does initializing an array mean?

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.


2 Answers

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};
like image 154
brymck Avatar answered Sep 21 '22 02:09

brymck


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.

like image 43
user113716 Avatar answered Sep 18 '22 02:09

user113716