5 回答
TA贡献1804条经验 获得超7个赞
查看Apple,Mozilla和Microsoft文档,该功能似乎仅限于处理字符串键/值对。
解决方法可以是在存储对象之前对其进行字符串化,然后在检索对象时对其进行解析:
var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
TA贡献1871条经验 获得超8个赞
对变体的微小改进:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));}Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);}由于短路评估,如果不在存储中getObject()则会立即返回。如果是(空字符串; 无法处理),它也不会抛出异常。nullkeySyntaxErrorvalue""JSON.parse()
TA贡献1829条经验 获得超13个赞
您可能会发现使用这些方便的方法扩展Storage对象很有用:
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));}Storage.prototype.getObject = function(key) {
return JSON.parse(this.getItem(key));}这样您就可以获得您真正想要的功能,即使API下面只支持字符串。
TA贡献1906条经验 获得超10个赞
扩展Storage对象是一个很棒的解决方案。对于我的API,我已经为localStorage创建了一个外观,然后在设置和获取时检查它是否是一个对象。
var data = {
set: function(key, value) {
if (!key || !value) {return;}
if (typeof value === "object") {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
},
get: function(key) {
var value = localStorage.getItem(key);
if (!value) {return;}
// assume it is an object that has been stringified
if (value[0] === "{") {
value = JSON.parse(value);
}
return value;
}}添加回答
举报
