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

我可以使用localStorage存储和检索原始JavaScript类型和数组,但对象似乎不起作用。他们应该吗?

这是我的代码:

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方法在存储输入之前将其转换为字符串。

我在Safari、Chrome和Firefox中看到了这种行为,所以我认为这是我对HTML5 Web存储规范的误解,而不是浏览器特定的错误或限制。

我已经试图理解2公共基础设施中描述的结构化克隆算法。我不完全理解它的意思,但也许我的问题与对象的财产不可枚举有关(???)。

有简单的解决方法吗?


更新:W3C最终改变了对结构化克隆规范的想法,并决定更改规范以匹配实现。请参阅12111–存储对象getItem(key)方法的规范与实现行为不匹配。因此,这个问题不再100%有效,但答案可能仍然令人感兴趣。


当前回答

有一个很棒的库,它封装了许多解决方案,因此它甚至支持称为jStorage的旧浏览器

可以设置对象

$.jStorage.set(key, value)

轻松检索

value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")

其他回答

localStorage.setItem('obj',JSON.stringify({name:'Akash'})); // Set Object in localStorage
localStorage.getItem('obj'); // Get Object from localStorage

sessionStorage.setItem('obj',JSON.stringify({name:'Akash'})); // Set Object in sessionStorage
sessionStorage.getItem('obj'); // Get Object from sessionStorage

我在读到另一篇文章后发表了这篇文章,这篇文章的标题是“如何在本地存储中存储数组?”。这很好,除了两个线程都没有提供关于如何在localStorage中维护数组的完整答案之外,不过我已经根据两个线程中包含的信息制定了一个解决方案。

因此,如果其他人希望能够在数组中推送/弹出/移动项目,并且他们希望将该数组存储在localStorage或sessionStorage中,那么可以这样做:

Storage.prototype.getArray = function(arrayName) {
  var thisArray = [];
  var fetchArrayObject = this.getItem(arrayName);
  if (typeof fetchArrayObject !== 'undefined') {
    if (fetchArrayObject !== null) { thisArray = JSON.parse(fetchArrayObject); }
  }
  return thisArray;
}

Storage.prototype.pushArrayItem = function(arrayName,arrayItem) {
  var existingArray = this.getArray(arrayName);
  existingArray.push(arrayItem);
  this.setItem(arrayName,JSON.stringify(existingArray));
}

Storage.prototype.popArrayItem = function(arrayName) {
  var arrayItem = {};
  var existingArray = this.getArray(arrayName);
  if (existingArray.length > 0) {
    arrayItem = existingArray.pop();
    this.setItem(arrayName,JSON.stringify(existingArray));
  }
  return arrayItem;
}

Storage.prototype.shiftArrayItem = function(arrayName) {
  var arrayItem = {};
  var existingArray = this.getArray(arrayName);
  if (existingArray.length > 0) {
    arrayItem = existingArray.shift();
    this.setItem(arrayName,JSON.stringify(existingArray));
  }
  return arrayItem;
}

Storage.prototype.unshiftArrayItem = function(arrayName,arrayItem) {
  var existingArray = this.getArray(arrayName);
  existingArray.unshift(arrayItem);
  this.setItem(arrayName,JSON.stringify(existingArray));
}

Storage.prototype.deleteArray = function(arrayName) {
  this.removeItem(arrayName);
}

示例用法-在localStorage数组中存储简单字符串:

localStorage.pushArrayItem('myArray','item one');
localStorage.pushArrayItem('myArray','item two');

示例用法-在sessionStorage阵列中存储对象:

var item1 = {}; item1.name = 'fred'; item1.age = 48;
sessionStorage.pushArrayItem('myArray',item1);

var item2 = {}; item2.name = 'dave'; item2.age = 22;
sessionStorage.pushArrayItem('myArray',item2);

处理数组的常用方法:

.pushArrayItem(arrayName,arrayItem); -> adds an element onto end of named array
.unshiftArrayItem(arrayName,arrayItem); -> adds an element onto front of named array
.popArrayItem(arrayName); -> removes & returns last array element
.shiftArrayItem(arrayName); -> removes & returns first array element
.getArray(arrayName); -> returns entire array
.deleteArray(arrayName); -> removes entire array from storage

有一个很棒的库,它封装了许多解决方案,因此它甚至支持称为jStorage的旧浏览器

可以设置对象

$.jStorage.set(key, value)

轻松检索

value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")

理论上,可以使用以下函数存储对象:

function store (a)
{
  var c = {f: {}, d: {}};
  for (var k in a)
  {
    if (a.hasOwnProperty(k) && typeof a[k] === 'function')
    {
      c.f[k] = encodeURIComponent(a[k]);
    }
  }

  c.d = a;
  var data = JSON.stringify(c);
  window.localStorage.setItem('CODE', data);
}

function restore ()
{
  var data = window.localStorage.getItem('CODE');
  data = JSON.parse(data);
  var b = data.d;

  for (var k in data.f)
  {
    if (data.f.hasOwnProperty(k))
    {
      b[k] = eval("(" + decodeURIComponent(data.f[k]) + ")");
    }
  }

  return b;
}

但是,函数序列化/反序列化不可靠,因为它依赖于实现。

下面是danott发布的代码的一些扩展版本:

它还将实现本地存储中的删除值,并显示如何添加Getter和Setter层,

localstorage.setItem(预览,true)

你可以写

config.preview=真

好了,我们来了:

var PT=Storage.prototype

if (typeof PT._setItem >='u')
  PT._setItem = PT.setItem;
PT.setItem = function(key, value)
{
  if (typeof value >='u') //..undefined
    this.removeItem(key)
  else
    this._setItem(key, JSON.stringify(value));
}

if (typeof PT._getItem >='u')
  PT._getItem = PT.getItem;
PT.getItem = function(key)
{
  var ItemData = this._getItem(key)
  try
  {
    return JSON.parse(ItemData);
  }
  catch(e)
  {
    return ItemData;
  }
}

// Aliases for localStorage.set/getItem
get = localStorage.getItem.bind(localStorage)
set = localStorage.setItem.bind(localStorage)

// Create ConfigWrapperObject
var config = {}

// Helper to create getter & setter
function configCreate(PropToAdd){
    Object.defineProperty( config, PropToAdd, {
      get: function ()    { return (get(PropToAdd)    )},
      set: function (val) {         set(PropToAdd, val)}
    })
}
//------------------------------

// Usage Part
// Create properties
configCreate('preview')
configCreate('notification')
//...

// Configuration Data transfer
// Set
config.preview = true

// Get
config.preview

// Delete
config.preview = undefined

嗯,你可以用.bind(…)去掉别名部分。不过,我只是把它放进去,因为知道这一点真的很好。我花了几个小时才弄明白为什么一个简单的get=localStorage.getItem;不工作。