【发布时间】:2015-10-29 05:32:38
【问题描述】:
我正在编写一个小库来操作 localStorage 中的数据。
下面是sn-p的代码:
function AppStorage (appName) {
"use strict";
var prefix = appName;
var saveItem = function (key, value) {
if (!key || !value) {
console.error("Missing parameters \"key\" and \"value\"");
return false;
}
if (window.localStorage && window['localStorage']) {
try {
if (typeof value === 'Object') localStorage.setItem(prefix + '_' + key, JSON.stringify(value));
if (typeof value === 'string') localStorage.setItem(prefix + '_' + key, value);
return true;
} catch (e) {
return false;
}
} else {
return false;
}
}
var getItem = function (key) {
if (!key) {
console.error("Missing parameter \"key\"");
return false;
}
if (window.localStorage && window['localStorage']) {
try {
return localStorage.getItem(prefix + '_' + key);
} catch (e) {
return false;
}
} else {
return false;
}
}
var removeItem = function (key) {
if (!key) {
console.error("Missing parameter \"key\"");
return false;
}
if (window.localStorage && window['localStorage']) {
try {
localStorage.removeItem(prefix + '_' + key);
return true;
} catch (e) {
return false;
}
} else {
console.log("Browser does not support HTML5 Web Storage");
}
}
return {
set: function (key, value) {
return saveItem(key, value);
},
get: function (key) {
return getItem(key);
},
remove: function (key) {
return removeItem(key);
}
}
}
var as = new AppStorage ('MyApp');
我是如何陷入以下两个问题的。
1) 当通过get() 检索数据时,存储的信息将作为string 返回。在传递之前,我需要以相同的格式接收此信息。
2) 下面的代码sn-p能否进一步改进。
【问题讨论】:
-
我猜你是在本地存储中存储对象?如果是这样,它们当然是字符串。您可以为每个存储的包含数据类型的数据添加另一个键,然后在 get() 方法中将其转换为正确的类型。
-
1) 尝试推送格式为
{type: 'mytype', data: 'mydata_ofmytype'}的对象,以便您始终可以知道所代表的类型。 2)为了什么目标进一步改进???这样的问题是?????? -
进一步改进是指代码在代码质量和设计方面如何进一步改进@morels
标签: javascript json html local-storage web-storage