Sixth: javascript: Dictionaries

Source: Internet
Author: User

A dictionary is a data structure stored as a key-value counterpart , just like the name and phone number in a phone book. Just find a phone, look for the name, the name is found, the phone number is found. The key value here is what you use to look for, and the value is the result to be checked.

The object class of JavaScript is designed in this dictionary form. This chapter uses the nature of the object class itself to implement a dictionary class that makes this type of object easier to use. You can also use arrays and objects to implement the methods presented in this chapter. But defining a dictionary class is more convenient and more interesting. For example, using () is simpler than using []. Of course, there are other conveniences, such as the ability to define a way to manipulate the whole, for example, to display all the elements in a dictionary, so that you do not have to use loops in the main program to traverse the entire dictionary .

One, Dictionary class

The dictionary class is based on the array class, not the object class. As we'll mention later in this chapter, we want to sort the keys in the dictionary, and the properties of the object cannot be sorted in JavaScript . But remember, JavaScript is all objects, and arrays are objects.

Start by defining the dictionary class with the following code:

    function Dictionary () {        thisnew  Array ();    }


First, define the Add () method, which accepts two parameters, keys, and values. The key is the index of the value in the dictionary. The code is as follows:

    function Add (key, value) {        this. Datastore[key] = value;    } 

Next, define the Find () method, which returns the value associated with the key as a parameter. The code looks like this:

    function Find (Key) {        returnthis. Datastore[key]    }


removes the key-value from the dictionary. You need to use a built-in function in javascript: delete. the function is part of the object class and uses a reference to the key as a parameter. The function also deletes the key and its irrelevant value. The following is the definition of remove ().

    function Remove (key) {        deletethis//Delete is part of the object class, using the key to delete the key and its irrelevant value.     }

Finally, we want to show all the key-value pairs in the dictionary, and here's a way to display them.

    function ShowAll () {        for (var in Object.keys (this . datastore)) {             this. Datastore[key])        }    }

The keys () method that finally calls object can return all the keys stored in the passed-in parameter.

Test method

    functionDictionary () { This. Add =add;  This. Datastore =NewArray ();  This. Find =find;  This. remove =remove;  This. ShowAll =ShowAll; }    //Add ()    functionAdd (key, value) { This. Datastore[key] =value; }    functionFind (key) {return  This. Datastore[key]}functionRemove (key) {Delete  This. Datastore[key]//Delete is part of the object class, using the key to delete the key and its irrelevant value.     }    functionShowAll () { for(varKeyinchObject.keys ( This. Datastore)) {//the keys () method that invokes object can return all keys stored in the passed-in parameterConsole.log (key + "+" + This. Datastore[key])} }    //Test    varPbook =NewDictionary (); Pbook.add ("Mike", "123"); Pbook.add ("David", "345"); Pbook.add ("Cynthia", "456"); Console.log ("David ' s Extension:" + pbook.find ("David");//David ' s extension:345Pbook.remove ("David"); Pbook.showall () Mike-> 123Cynthia-> 456

Second, the auxiliary method of dictionary class

We can also define some helper methods that are useful in certain situations, such as the number of elements in a statistical dictionary

    function count () {        var n = 0;          for (var in Object.keys (this. datastore)) {            + +n;        }    }

At this point, you might ask why the length property is used, because when the type of the key is a string, the length property is no use . Test:

    var New Array ();    nums[0] = 1;    nums[1] = 2;     // 2     Pbook.add ("Mike", "123");    Pbook.add ("David", "345");    Console.log (pbook.length); // undefined

Clear () is another helper method, defined as follows:

    function Clear () {        for all (var in Object.keys (this . datastore)) {             Deletethis. Datastore[key];        }    }

Third, add sort function to dictionary class

The purpose of a dictionary is primarily to use key values, and we don't need to be too concerned with the actual order in which the data is stored in the dictionary. However, many people want to see an orderly dictionary. Here's a look at how to implement the dictionary display in order.

Arrays can be sorted.

As follows.

    var New Array ();    a[0] = "Mike";    a[1] = "David";    Console.log (a); // ["Mike", "David"]     A.sort ();     // ["David", "Mike"]

But the above approach is not valid in a dictionary with a string as the key, and the program will not have any output. This is the same situation we encountered when we defined the count () method.

However, this is not a big problem, the user is concerned about the display of the contents of the dictionary, the result is orderly. You can use the Object.keys () function to solve this problem. Here's how to redefine ShowAll ().

    function showAll2 () {        for (var -Object.keys (this . datastore). Sort ()) {              This . Datastore[key])        }    }

The only difference between this definition and the previous definition is that when you get the key from the array datastore, the sort () method is called to reorder the keys.

    functionDictionary () { This. Add =add;  This. Datastore =NewArray ();  This. Find =find;  This. remove =remove;  This. ShowAll =ShowAll;  This. ShowAll2 =showAll2;  This. Count =count; //this.clear = clear;    }    //Add ()    functionAdd (key, value) { This. Datastore[key] =value; }    functionFind (key) {return  This. Datastore[key]}functionRemove (key) {Delete  This. Datastore[key]//Delete is part of the object class, using the key to delete the key and its irrelevant value.     }    functionShowAll () { for(varKeyinchObject.keys ( This. Datastore)) {//the keys () method that invokes object can return all keys stored in the passed-in parameterConsole.log (key + "+" + This. Datastore[key])} }    functionshowAll2 () { for(varKeyinchObject.keys ( This. datastore. Sort ()) {//when the contents of the dictionary are displayed, the result is orderly. Use the Object.keys () function. Console.log (key + "+" + This. Datastore[key])} }    functioncount () {varn = 0;  for(varKeyinchObject.keys ( This. Datastore)) {            ++N; } console.log (n)}//function Clear () {    //For each (Var key in Object.keys (This.datastore)) {    //Delete This.datastore[key];    //     }    // }    //Test    varPbook =NewDictionary (); Pbook.add ("Mike", "123"); Pbook.add ("David", "345"); Pbook.add ("Cynthia", "456"); Console.log ("David ' s Extension:" + pbook.find ("David");//David ' s extension:345Pbook.remove ("David"); Pbook.showall () Pbook.count ( )//2    //pbook.clear ()Pbook.showall2 ()

( end of chapter )

Previous chapter: Fifth: javascript: Queue Next Chapter: Chapter Seventh: javascript: Hashing

Sixth: javascript: Dictionaries

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.