Javascript array and dictionary usage analysis
- 2020-05-05 10:53:23
- OfStack
This article analyzes the Javascript array and dictionary usage as an example. Share with you for your reference. The specific analysis is as follows:
Javascript array Array, is both an array and a dictionary (Dictionary).
Let's start with an example of array usage.
var a = new Array();
a[0] = "Acer";
a[1] = "Dell";
for (var i in a) {
alert(i);
}
The above code creates an array where each element is a string object.
The array is then traversed. Note that i results in 0 and 1, a[i] results in string.
This is very much like the previous article about traversing the properties of an object.
Now let's look at the dictionary usage.
var computer_price = new Array();
computer_price["Acer"] = 500;
computer_price["Dell"] = 600;
alert(computer_price["Acer"]);
We can even traverse the array (dictionary)
as above
for (var i in computer_price) {
alert(i + ": " + computer_price[i]);
}
i here is each key value of the dictionary. The output is:
Acer: 500
Dell: 600
Now, let's see what's interesting about Javascript, again, the example above.
We can think of computer_price as a dictionary object, and each of its key values is an attribute.
That is, Acer is an attribute of computer_price. We can use it like this: computer_price.Acer
Let's take a look at simplified declarations for dictionaries and arrays.
var array = [1, 2, 3]; // An array of
var array2 = { "Acer": 500, "Dell": 600 }; // The dictionary
alert(array2.Acer); // 50
So the dictionary declaration is the same as before. In our example, Acer is again a key and an attribute of the dictionary object.
I hope that this article has been helpful to your javascript programming.