Skip to main content

缓存请求结果

const fn = (function () {
const cache = {}; //用来缓存的对象
return function (val) {
if (!(val in cache)) {
cache[val] = getRandomArray(val);
}
return cache[val];
};
})();
console.log(fn("data1")); // 调用 getRandomArray 函数,返回一组数据,以“datal’作为key,存储到 cache 中
console.log(fn("data2")); // 调用 getRandomArray 函数,返回一组数据,以“data2”作为key,存储到cache 中
console.log(fn("data1")); // 执行该代码不会再调用getRandomArray函数,直接返回第一次执行fn('data1')返回的数据
/*--
----以下是内置代码,无需改动----
*/
// 模拟服务器返回的数据
function getRandomArray(key) {
var randomArray = [];
for (var i = 0; i < 10; i++) {
var randomNum = Math.floor(Math.random() * (1000 + 1)) + 0;
randomArray.push(randomNum);
}
return randomArray;
}