Dictionary is often called a data dictionary, is a data structure used to hold key-value pairs, such as our daily phone book, is a dictionary. We can access the corresponding value (phone number) by the key (name). In C + + and Java We all use map to build such a dictionary, but the name is different. In JavaScript, an object is like a dictionary, because an object is a collection of property name/property values.
To better reflect the dictionary, we can build an easy-to-use dictionary class based on array and object:
Dictionary class:
functionDictionary () { This. DataArray = []; //adding elements This. Add =function(key, item) { This. Dataarray[key] =item; }; //Find Element This. Find =function(key) {return This. Dataarray[key]; }; //Delete Element This. remove =function(key) {Delete This. Dataarray[key]; }; //display Element This. Showallitems =function (){ for(varKeyinchObject.keys ( This. DataArray)) {Console.log (Key+ ":" + This. Dataarray[key]); } } }</script></body>In addition to the above methods, we can also add other methods and properties according to our own use.
Delete all elements in a dictionary
This function () { for (var . Object.keys ( this . DataArray)) { deletethis. Dataarray[key]; } ;
the number of elements in the dictionary
Thisfunction () { var num = 0; for (var in Object.keys (this. DataArray)) { + +num; } return num; }
The number of queries in Itemscount why not use This.dataArray.length directly??? This is because when the type of the key is a string type, the length property has no effect ....
The use of dictionaries most of the time we care about the key to get the value, do not care about the order of the keys, but in order to better display the phone book we said earlier, you can sort the key (name) in the phone book.
It's common in JavaScript to sort an array, and then you'll see silently, using the sort () of arrays. The main reason is that we usually use arrays in the array according to the integer value of the index under the array elements are sorted, now the index of the arrays into a string, this form of sorting also lost its effect. We can actually remove the key from the dictionary, put the key in an array a, then sort the array a, and then use array A to traverse the dictionary. Object.keys () provides a way to:
This function () { for (var -Object.keys (this . DataArray). Sort ()) { this. Dataarray[key]); } }
So that we can implement the "key" to sort out ...
JavaScript Dictionary Data Structures