Create a dictionary object (dictionary) instance in JavaScript

  • 2020-05-24 05:10:24
  • OfStack

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


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 is to create a cache of compiled results, the code is called as follows:


var codecache = createCache();

In the source code, keys is used to save keys, and cache object is used to save key-value pairs, and through the global variable Expr.cacheLength control the maximum number of keys, if more than the number, automatically delete the first key and key-value pair.
This code takes advantage of the structure of closures to make the keys variable inaccessible to external code, thus ensuring the security of the keys variable. Of course, because of the nature of the JavaScript statement, the external code can still change the cache property to make the key-value pair not match. However, as long as not deliberately spoof, this itself should not matter too much.

Of course, it also can't pledge a complete dictionary object, because it doesn't provide key functions such as the judgment of primary key repetition, and interested friends can improve it.


Related articles: