SoFunction
Updated on 2025-03-03

Create a dictionary instance in JavaScript

For JavaScript, its own Array object is just an array and cannot provide the data saved through keywords. jQuery source code provides a very good way to solve this problem. Let's take a look at the source code first:

Copy the 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 ((key += " ") > ) {
   // Only keep the most recent entries
   delete cache[()];
  }
  return (cache[key] = value);
 }
 return cache;
}

The above source code creates a cache of compilation results, and the code is called as follows:

Copy the codeThe code is as follows:

var codecache = createCache();

In the source code, keys are used to save keys, while cache objects are used to save key-value pairs, and control the maximum number of keys through global variables. If this number exceeds, the first key and key-value pair will be automatically deleted.
This code utilizes the structure of the closure, making it impossible for external code to access the keys variable, so that the security of the keys variable can be ensured. Of course, due to the characteristics of JavaScript statements, external code can still modify the cache attribute to make the key and key-value pairs not match. However, as long as you don't deliberately make a spoof, this itself shouldn't have much to do with it.

Of course, it cannot swear a perfect dictionary object, because it does not provide key functions such as judgment of primary key duplication, and friends who are interested can improve it.