Creating a Dictionary object (dictionary) instance in JavaScript _javascript tips

Source: Internet
Author: User
Tags delete cache

For JavaScript, its own array object is only a number of arrays, can not provide through the keyword to obtain the saved data, jquery source provides a very good way to solve the problem, first look at the source code:

Copy Code code as follows:

function Createcache () {
var keys = [];

function cache (key, value) {
Use (key + "") to avoid collision with native prototype
Properties (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 is to create a compilation of the results of the cache, the code calls the following way:

Copy Code code as follows:

var codecache = Createcache ();

Source code, the keys used to save the key, and the cache object to save the key value pairs, and through the global variable expr.cachelength the maximum number of control keys, if more than that number, then automatically delete the first key and key value pairs.
This code makes use of the closure structure so that the external code cannot access the keys variable, which ensures the security of the keys variable. Of course, because of the characteristics of JavaScript statements, external code can also modify the cache property so that the key and key value pairs do not match. However, as long as not deliberately spoof, this itself should not have much relationship.

Of course, it also cannot swear a perfect dictionary object, because it does not provide key functions such as duplicate judgment of the primary key, and interested friends can refine 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: 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.