Create a dictionary object (dictionary) instance in JavaScript and a typical javascript instance

Source: Internet
Author: User
Tags delete cache

Create a dictionary object (dictionary) instance in JavaScript and a typical javascript instance

For JavaScript, its own Array object is only an Array and cannot be used to obtain the stored data through keywords. jQuery source code provides a very good way to solve this problem, first look at the source code:

Copy codeThe Code is as follows:
Function createCache (){
Var keys = [];

Function cache (key, value ){
// Use (key + "") to avoid collision with native prototype
// Properties (see Issue #157)
If (keys. push (key + = "")> Expr. cacheLength ){
// Only keep the most recent entries
Delete cache [keys. shift ()];
}
Return (cache [key] = value );
}
Return cache;
}

The above Source Code creates a cache for the compilation result. The Code call method is as follows:

Copy codeThe Code is as follows:
Var codecache = createCache ();

In the source code, keys is used to save the key, and the cache object is used to save the key-value pair, and the global variable Expr is used. the maximum number of cacheLength control keys. If the maximum number is exceeded, the first key and key-value pair are automatically deleted.
This Code uses the closure structure to prevent external code from accessing the keys variable. This ensures the security of the keys variable. Of course, due to the characteristics of JavaScript statements, external code can still modify the cache attribute to make the key-value pair do not match. However, as long as you do not intentionally spoof it, it should not be too relevant.

Of course, it cannot swear a perfect dictionary object, because it does not provide key functions such as primary key duplicate judgment. Interested friends can perfect it.

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.