在html5中怎么使用localStorage中存储对象?案例详解!

猿友 2021-07-30 10:20:13 浏览数 (1497)
反馈

在开发中我们需要将对象进行一个存储的步骤,那么今晚小编就和大家讨论一下有关于:“在html5中怎么使用localStorage中存储对象?”这个问题,下面是小编整理的相关内容分享,希望可以帮助到大家!

我想在HTML5中存储一个JavaScript对象localStorage,但是我的对象显然正在转换为字符串。

我可以使用来存储和检索原始JavaScript类型和数组localStorage,但是对象似乎无法正常工作。应该吗

这是我的代码:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
console.log('typeof testObject: ' + typeof testObject);
console.log('testObject properties:');
for (var prop in testObject) {
    console.log('  ' + prop + ': ' + testObject[prop]);
}

// Put the object into storage
localStorage.setItem('testObject', testObject);

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('typeof retrievedObject: ' + typeof retrievedObject);
console.log('Value of retrievedObject: ' + retrievedObject);

控制台输出为

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

在我看来,该setItem方法是在存储输入之前将输入转换为字符串。

解决方案:

再次查看Apple,Mozilla和Mozilla文档,该功能似乎仅限于处理字符串键/值对。

一种解决方法是在存储对象之前先对它进行字符串化处理,然后在检索它时对其进行解析:

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));

通过改文章的分享相信很多小伙伴们对于:“在html5中怎么使用localStorage中存储对象”这方面的相关内容也有了不少的了解,对于html5这方面有感兴趣的小伙伴们都可以在W3Cschool中进行个系统的学习! 


0 人点赞