/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
//把键值存放在keys
var keys = [];
//返回一个缓存函数
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > 3 ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];//shift()方法用于把数组的第一个元素从其中删除,并返回第一个元素的值
}
//把值放在cache函数的属性上,即,cache.name = 'myname'
return (cache[ key + " " ] = value);
}
return cache;
}
var tokenCache = createCache();
console.log(tokenCache("name","myname"));
console.log(tokenCache("name2","myname2"));
console.log(tokenCache("name3","myname3"));
console.log(tokenCache("name4","myname4"));
console.log("=====");
for(var v in tokenCache){
console.log(tokenCache[v]);
}
jQuery的缓存函数
如果已经超过了缓存的数量,则先缓存的先删除
push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。
shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。
即所谓的先进先出