我正在从一个阵列项目的方式,只要它不存在,那么存储失败后,在localStorage
的JavaScript Array.indexOf()使用本地存储
var queue = [];
function moveToQueue(item) {
if(queue.indexOf(item) == -1) {
queue.push(item);
store();
}
}
function store() {
localStorage.myApp_queue = JSON.stringify(queue);
}
页面加载时,我打电话给我的加载功能。
function load() {
if(typeof localStorage.myApp_queue != 'undefined') {
queue = JSON.parse(localStorage.myApp_queue);
}
}
在这一点上,我的界面显示queue
,因为我已经离开了最后,但如果我尝试再次添加同一项目中,“queue.indexOf(项目)”失败。 queue
的内容与调用store()/load()
方法之前的内容不同。
以下是我的页面重新加载之前和之后的一些console.log()
调用,从空的queue
开始。日志已经被添加到moveToQueue
功能开始
function moveToQueue(item) {
console.log('adding to queue');
console.log(item);
console.log(queue[0]);
console.log(queue.indexOf(item));
...
初始负载:
adding to queue
e {id: 1, status: "A", title: "Comcar", $$hashKey: "004", $get: function…}
undefined
-1
adding to queue
e {id: 1, status: "A", title: "Comcar", $$hashKey: "004", $get: function…}
e {id: 1, status: "A", title: "Comcar", $$hashKey: "004", $get: function…}
0
页面刷新后 - 我推的项目已经是queue
阵列中
adding to queue
e {id: 1, status: "A", title: "Comcar", $$hashKey: "006", $get: function…}
Object {id: 1, status: "A", title: "Comcar", $$hashKey: "004"}
-1
我在这里错过了什么,localStorage
和JSON
做什么来改变我的阵列。
我可以看到日志列出从存储返回的项目为“对象”,而原始项目具有“类型”(不太确定)“e”。
如果我使用typeof
两个结果是“对象”
啊,我刚刚意识到一些事情。原来的项目有getter,setter等,它们似乎是真正的javascript对象。那些在localStorage中进行解析/解析的只是简单的字典/键值对!所以我需要阻止他们成为复杂的对象?我想 – 2013-02-19 12:33:36
我在我的代码所做的更改,现在它将为复杂对象的工作太:-) – 2013-02-19 12:58:09