gpt4 book ai didi

javascript - 在javascript中缓存对象

转载 作者:行者123 更新时间:2023-11-30 05:54:51 25 4
gpt4 key购买 nike

我有一个使用此代码的闹鬼:

javascript代码:

var cache = {};

cache.init = function()
{
if(typeof(this.memory)=='undefined')
this.memory = {};
};

cache.set = function(key, value)
{
this.memory[key] = value;
};

cache.get = function(key)
{
if(console)
{
console.log("memory: ");
console.log(cache.memory);

console.log("key: "+key);
console.log(cache.memory[key]);
}

if(typeof(cache.memory[key])!='undefined')
return cache.memory[key];

return false;
};

var route = {};

route.load = function(url)
{
var route_list = cache.get('route_list');

if(route_list==false)
{
route_list = this.getList();
cache.set('route_list', route_list);
}

return route_list;
};

route.getList = function()
{
var result = false;
$.ajax(
{
url: 'route.json',
dataType: 'json',
async: false,
success: function(json)
{
result = json;
}
});
return result;
};

cache.init();
route.load();
route.load();

我想在客户端缓存一些对象,设置并获取“缓存”。

route.json文件内容:

{    
"/example":
{
"controller": "example"
},
"/example/show":
{
"controller": "example",
"method": "show"
}
}

在 Firebug 中的结果是:

memory:
Object
{
route_list
Object { /example={...}, /example/show={...}}
}
key: route_list
undefined

为什么是未定义的?我可以使用 firebug o.O 在对象内部导航

编辑:我添加了 route.load() 的第二次调用;我得到未定义的 key

最佳答案

好的,现在我可以看到你的问题了。你的代码

route.load();
route.load();
  1. 尝试从缓存中获取 [uncached] 值:
    1. 这记录了内存对象
    2. 并记录 undefined 因为什么都没有
  2. 因为它返回 false
    1. 同步获取JSON
    2. 并设置到缓存中
  3. 再次尝试获取[缓存]值
    1. 记录内存对象
    2. 并记录缓存的对象

一切都正确执行。现在,您在控制台中看到内存对象两次 - 但它是同一个对象,检查时处于当前状态,而不是记录时的状态。另见

关于javascript - 在javascript中缓存对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12563565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com