我想在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%有效,但答案可能仍然令人感兴趣。


当前回答

我找到了一种方法,使它可以处理具有循环引用的对象。

让我们制作一个具有循环引用的对象。

obj = {
    L: {
        L: { v: 'lorem' },
        R: { v: 'ipsum' }
    },
    R: {
        L: { v: 'dolor' },
        R: {
            L: { v: 'sit' },
            R: { v: 'amet' }
        }
    }
}
obj.R.L.uncle = obj.L;
obj.R.R.uncle = obj.L;
obj.R.R.L.uncle = obj.R.L;
obj.R.R.R.uncle = obj.R.L;
obj.L.L.uncle = obj.R;
obj.L.R.uncle = obj.R;

由于循环引用,我们不能在这里执行JSON.stringify。

LOCALSTORAGE.CYCLICJSON与普通JSON一样具有.stringify和.parse,但可以处理具有循环引用的对象。(“Works”表示解析(stringify(obj))和obj深度相等,并且具有相同的“内部等式”集合)

但我们可以使用快捷方式:

LOCALSTORAGE.setObject('latinUncles', obj)
recovered = LOCALSTORAGE.getObject('latinUncles')

然后,recovered将与obj“相同”,在以下意义上:

[
obj.L.L.v === recovered.L.L.v,
obj.L.R.v === recovered.L.R.v,
obj.R.L.v === recovered.R.L.v,
obj.R.R.L.v === recovered.R.R.L.v,
obj.R.R.R.v === recovered.R.R.R.v,
obj.R.L.uncle === obj.L,
obj.R.R.uncle === obj.L,
obj.R.R.L.uncle === obj.R.L,
obj.R.R.R.uncle === obj.R.L,
obj.L.L.uncle === obj.R,
obj.L.R.uncle === obj.R,
recovered.R.L.uncle === recovered.L,
recovered.R.R.uncle === recovered.L,
recovered.R.R.L.uncle === recovered.R.L,
recovered.R.R.R.uncle === recovered.R.L,
recovered.L.L.uncle === recovered.R,
recovered.L.R.uncle === recovered.R
]

以下是LOCALSTORAGE的实现

LOCALSTORAGE=(函数){“使用严格”;var ignore=[Boolean,Date,Number,RegExp,String];函数原语(项){if(项目类型==“对象”){if(item==null){return true;}对于(var i=0;i<ignore.length;i++){if(iteminstanceofignore[i]){return true;}}return false;}其他{返回true;}}功能婴儿(价值){return Array.isArray(value)?[] : {};}函数decycleIntoForest(对象,替换符){if(typeof replacer!==“函数”){replacer=函数(x){return x;}}object=替换器(对象);if(原语(对象))返回对象;var objects=[对象];var森林=[婴儿(对象)];var bucket=new WeakMap();//桶=对象的倒数bucket.set(对象,0);函数addToBucket(obj){var result=objects.length;objects.push(obj);bucket.set(对象,结果);返回结果;}函数isInBucket(obj){return bucket.has(obj);}函数processNode(源,目标){Object.keys(源).forEach(函数(键){var value=replacer(源[key]);if(基元(值)){target[key]={value:value};}其他{var ptr;if(isInBucket(值)){ptr=bucket.get(值);}其他{ptr=addToBucket(值);var newTree=婴儿(值);forest.push(newTree);processNode(value,newTree);}target[key]={pointer:ptr};}});}processNode(对象,林[0]);回归森林;};函数deForestInoCycle(林){var对象=[];var objectRequested=[];var todo=[];函数processTree(idx){if(对象中的idx)返回对象[idx];if(objectRequested[idx])返回null;objectRequested[idx]=true;var树=森林[idx];var node=Array.isArray(树)?[] : {};for(树中的var键){var o=树[key];如果(o中的“指针”){var ptr=o.pointer;var value=processTree(ptr);if(值==空){todo推送({node:节点,key:键,idx:ptr});}其他{node[key]=值;}}其他{if(o中的“值”){节点[key]=o.value;}其他{抛出新错误(“意外”)}}}objects[idx]=节点;返回节点;}var result=processTree(0);对于(var i=0;i<todo.length;i++){var项=todo[i];item.node[item.key]=对象[item.idx];}返回结果;};var控制台={日志:函数(x){var the=document.getElementById(''');.textContent=.textContent+'\n'+x;},分隔符:函数(){var the=document.getElementById(''');.textContent=.textContent+'\n***************************************';}}函数logCyclicObjectToConsole(根){var cycleFree=decycleIntoForest(根);var showed=cycleFree.map(函数(树,idx){return false;});var缩进增量=4;函数showItem(nodeSlot、indent、label){var leadingSpaces=''.repeat(缩进);var leadingSpacesPlus=“”.repeat(缩进+缩进增量);if(显示[nodeSlot]){console.log(leadingSpaces+label+'…请参见上文(object#'+nodeSlot+')');}其他{console.log(leadingSpaces+label+'object#'+nodeSlot);var tree=cycleFree[nodeSlot];show[nodeSlot]=true;Object.keys(树).forEach(函数(键){var entry=tree[key];if(条目中的“值”){console.log(leadingSpacesPlus+key+“:”+entry.value);}其他{if(条目中的“指针”){showItem(entry.pointer,indent+indentIncrement,key);}}});}}console.demiter();showItem(0,0,'root');};函数字符串(obj){return JSON.stringify(decycleIntoForest(obj));}函数解析(str){return deForestInoCycle(JSON.parse(str));}var CYLICJSON={decycleIntoForest:decycleIntoForest,deForestInoCycle:deForestIntoCycle,logCyclicObjectToConsole:logCyclicObject到控制台,丝状:丝状,解析:解析}函数setObject(名称,对象){var str=字符串(对象);localStorage.setItem(名称,str);}函数getObject(名称){var str=localStorage.getItem(名称);如果(str==null)返回null;返回解析(str);}返回{CYCLICJSON:CYCLICJSON,setObject:setObject,getObject:getObject}})();目标={我:{五十: {v:“lorem”},R: {v:“ipsum”}},R:{五十: {v:“dolor”},R:{五十: {v:“坐”},R: {v:“amet”}}}}obj.R.L.uncle=对象L;obj.R..uncle=对象L;obj.R.L..uncle=obj.R.L;obj.R.R..uncle=obj.R.L;obj.L.L.uncle=对象R;obj.L.R.unncle=对象R;//LOCALSTORAGE.setObject(“latinUncles”,对象)//recovered=LOCALSTORAGE.getObject('latinUncles')//fiddle内部不提供localStorage):本地存储.CYCLICJSON.logCyclicObjectToConsole(obj)putIntoLS=本地存储.CYCLICJSON.stringify(obj);recovered=本地存储.CYCLICJSON.parse(putIntoLS);LOCALSTORAGE.CYCLICJSON.logCyclicObjectToConsole(已恢复);var the=document.getElementById(''');.textContent=.textContent+'\n\n'+JSON.stringify([目标L.L.v===恢复L.L.v,目标L.R.v===恢复L.R.v,目标R.L.v===恢复的R.L.v,目标R.R.L.v===恢复的R.R.L.v,obj.R.R.R.v===恢复的R.R.R.v,obj.R.L.包含==obj.L,

其他回答

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

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

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

我在读到另一篇文章后发表了这篇文章,这篇文章的标题是“如何在本地存储中存储数组?”。这很好,除了两个线程都没有提供关于如何在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

您可以使用localDataStorage透明地存储JavaScript数据类型(Array、BigInt、Boolean、Date、Float、Integer、String和Object)。它还提供了轻量级数据混淆,自动压缩字符串,方便按关键字(名称)和按关键字(值)查询,并通过前缀关键字帮助在同一域内强制执行分段共享存储。

[免责声明]我是实用程序的作者[/免责声明】

示例:

localDataStorage.set( 'key1', 'Belgian' )
localDataStorage.set( 'key2', 1200.0047 )
localDataStorage.set( 'key3', true )
localDataStorage.set( 'key4', { 'RSK' : [1,'3',5,'7',9] } )
localDataStorage.set( 'key5', null )

localDataStorage.get( 'key1' )  // -->   'Belgian'
localDataStorage.get( 'key2' )  // -->   1200.0047
localDataStorage.get( 'key3' )  // -->   true
localDataStorage.get( 'key4' )  // -->   Object {RSK: Array(5)}
localDataStorage.get( 'key5' )  // -->   null

正如您所看到的,基本值受到了尊重。

另一种选择是使用现有的插件。

例如,persisto是一个开源项目,它为localStorage/sessionStorage提供了一个简单的接口,并自动实现表单字段(输入、单选按钮和复选框)的持久性。

(免责声明:我是作者。)

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

可以设置对象

$.jStorage.set(key, value)

轻松检索

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