For JavaScript, its own Array object is just an array and cannot provide access to saved data through keywords. The jQuery source code provides a very good way to solve this problem. Take a look at the source code first:
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 compilation results. The code is called as follows:
In the source code, keys are used to save keys, while cache objects are used to save key-value pairs, and the maximum number of keys is controlled through the global variable Expr.cacheLength. If this number is exceeded, the first key and key value will be automatically deleted. right.
This code uses the closure structure to prevent external code from accessing the keys variable, thus ensuring the security of the keys variable. Of course, due to the characteristics of JavaScript statements, external code can still make the keys and key-value pairs mismatch by modifying the cache attributes. However, as long as you don't deliberately make a prank, this in itself shouldn't matter much.
Of course, it cannot declare a complete dictionary object because it does not provide key functions such as primary key duplication judgment. Interested friends can improve it.