Home > Web Front-end > JS Tutorial > Create dictionary object (dictionary) instance in JavaScript_javascript tips

Create dictionary object (dictionary) instance in JavaScript_javascript tips

WBOY
Release: 2016-05-16 16:06:47
Original
2196 people have browsed it

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:

Copy code The 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 is to create a cache of compilation results. The code is called as follows:

Copy code The 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 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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template