在HTML5 localStorage中存储对象

这篇博客探讨了在HTML5的localStorage中存储JavaScript对象时遇到的问题,特别是对象被转换为字符串的问题。文章讨论了JSON.stringify()的局限性,包括处理循环引用和私有成员,以及不同浏览器的行为。解决方案包括在存储和检索时手动进行字符串化和解析。博客还提到了其他存储库和扩展Storage对象的方法,以支持更复杂的对象存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

我可以使用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存储规范的误解,而不是浏览器特定的错误或限制。

我试图弄清http://www.w3.org/TR/html5/infrastructure.html中描述的结构化克隆算法。 我不完全明白这是什么意思,但也许我的问题与我的对象的属性不可枚举有关(???)

有一个简单的解决方法吗?


更新:W3C最终改变了对结构化克隆规范的想法,并决定更改规范以匹配实现。 参见https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 。 因此,此问题不再100%有效,但答案可能仍然很有趣。


#1楼

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

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

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

#2楼

您可能会发现使用以下方便的方法扩展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下仅支持字符串,您也可以获得真正想要的功能。


#3楼

在碰到另一篇已与此副本重复的帖子之后,我到达了这篇文章。这篇文章的标题为“如何在本地存储中存储数组?”。 很好,除非两个线程都不能真正提供有关如何在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

#4楼

一个使用localStorage跟踪来自联系人的消息的库的小示例:

// This class is supposed to be used to keep a track of received message per contacts.
// You have only four methods:

// 1 - Tells you if you can use this library or not...
function isLocalStorageSupported(){
    if(typeof(Storage) !== "undefined" && window['localStorage'] != null ) {
         return true;
     } else {
         return false;
     }
 }

// 2 - Give the list of contacts, a contact is created when you store the first message
 function getContacts(){
    var result = new Array();
    for ( var i = 0, len = localStorage.length; i < len; ++i ) {
        result.push(localStorage.key(i));
    }
    return result;
 }

 // 3 - store a message for a contact
 function storeMessage(contact, message){
    var allMessages;
    var currentMessages = localStorage.getItem(contact);
    if(currentMessages == null){
        var newList = new Array();
        newList.push(message);
        currentMessages = JSON.stringify(newList);
    }
    else
    {
        var currentList =JSON.parse(currentMessages);
        currentList.push(message);
        currentMessages = JSON.stringify(currentList);
    }
    localStorage.setItem(contact, currentMessages);
 }

 // 4 - read the messages of a contact
 function readMessages(contact){

    var result = new Array();
    var currentMessages = localStorage.getItem(contact);

    if(currentMessages != null){
        result =JSON.parse(currentMessages);
    }
    return result;
 }

#5楼

@Guria的答案的改进:

Storage.prototype.setObject = function (key, value) {
    this.setItem(key, JSON.stringify(value));
};


Storage.prototype.getObject = function (key) {
    var value = this.getItem(key);
    try {
        return JSON.parse(value);
    }
    catch(err) {
        console.log("JSON parse failed for lookup of ", key, "\n error was: ", err);
        return null;
    }
};

#6楼

http://rhaboo.org是localStorage糖层,可让您编写如下内容:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');

它不使用JSON.stringify / parse,因为在大对象上这将是不准确且缓慢的。 而是,每个终端值都有其自己的localStorage条目。

您可能会猜到我可能与rhaboo有关;-)

阿德里安


#7楼

Stringify不能解决所有问题

似乎这里的答案并未涵盖JavaScript中所有可能的类型,因此以下是一些有关如何正确处理它们的简短示例:

//Objects and Arrays:
    var obj = {key: "value"};
    localStorage.object = JSON.stringify(obj);  //Will ignore private members
    obj = JSON.parse(localStorage.object);
//Boolean:
    var bool = false;
    localStorage.bool = bool;
    bool = (localStorage.bool === "true");
//Numbers:
    var num = 42;
    localStorage.num = num;
    num = +localStorage.num;    //short for "num = parseFloat(localStorage.num);"
//Dates:
    var date = Date.now();
    localStorage.date = date;
    date = new Date(parseInt(localStorage.date));
//Regular expressions:
    var regex = /^No\.[\d]*$/i;     //usage example: "No.42".match(regex);
    localStorage.regex = regex;
    var components = localStorage.regex.match("^/(.*)/([a-z]*)$");
    regex = new RegExp(components[1], components[2]);
//Functions (not recommended):
    function func(){}
    localStorage.func = func;
    eval( localStorage.func );      //recreates the function with the name "func"

我不建议存储函数,因为eval()是邪恶的,可能导致有关安全性,优化和调试的问题。 通常,不应在JavaScript代码中使用eval()

私人会员

使用JSON.stringify()存储对象的问题是,此函数无法序列化私有成员。 可以通过覆盖.toString()方法(在Web存储中存储数据时隐式调用.toString()解决此问题:

//Object with private and public members:
    function MyClass(privateContent, publicContent){
        var privateMember = privateContent || "defaultPrivateValue";
        this.publicMember = publicContent  || "defaultPublicValue";

        this.toString = function(){
            return '{"private": "' + privateMember + '", "public": "' + this.publicMember + '"}';
        };
    }
    MyClass.fromString = function(serialisedString){
        var properties = JSON.parse(serialisedString || "{}");
        return new MyClass( properties.private, properties.public );
    };
//Storing:
    var obj = new MyClass("invisible", "visible");
    localStorage.object = obj;
//Loading:
    obj = MyClass.fromString(localStorage.object);

循环参考

stringify无法处理的另一个问题是循环引用:

var obj = {};
obj["circular"] = obj;
localStorage.object = JSON.stringify(obj);  //Fails

在此示例中, JSON.stringify()将引发TypeError “将圆形结构转换为JSON” 。 如果应该支持存储循环引用,则可以使用JSON.stringify()的第二个参数:

var obj = {id: 1, sub: {}};
obj.sub["circular"] = obj;
localStorage.object = JSON.stringify( obj, function( key, value) {
    if( key == 'circular') {
        return "$ref"+value.id+"$";
    } else {
        return value;
    }
});

但是,找到一种有效的解决方案来存储循环引用在很大程度上取决于需要解决的任务,并且恢复此类数据也不是一件容易的事。

因此,已经有一些关于SO处理此问题的问题: Stringify(转换为JSON)具有循环引用的JavaScript对象


#8楼

使用JSON对象进行本地存储:

//组

var m={name:'Hero',Title:'developer'};
localStorage.setItem('us', JSON.stringify(m));

//得到

var gm =JSON.parse(localStorage.getItem('us'));
console.log(gm.name);

//迭代所有本地存储键和值

for (var i = 0, len = localStorage.length; i < len; ++i) {
  console.log(localStorage.getItem(localStorage.key(i)));
}

//删除

localStorage.removeItem('us');
delete window.localStorage["us"];

#9楼

这是@danott发布的代码的扩展版本

它还将实现从localstorage 删除值,并说明如何添加Getter和Setter层,而不是

localstorage.setItem(preview, true)

你可以写

config.preview = true

好了,去了:

var PT=Storage.prototype

if (typeof PT._setItem >='u') PT._setItem = PT.setItem;
PT.setItem = function(key, value)
{
  if (typeof value >='u')//..ndefined
    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')
//...

// Config Data transfer
//set
config.preview = true

//get
config.preview

// delete
config.preview = undefined

好吧,您可以使用.bind(...)别名部分。 但是我只是把它放进去,因为了解这一点真的很好。 我花了几个小时来找出为什么简单的get = localStorage.getItem; ;。 不工作


#10楼

建议使用抽象库来实现此处讨论的许多功能以及更好的兼容性。 很多选择:


#11楼

变体的小改进:

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

由于短路评估 ,如果key不在Storage中,则getObject()立即返回null 。 如果value"" (空字符串; JSON.parse()无法处理),它也不会引发SyntaxError异常。


#12楼

我所做的事情不会破坏现有的Storage对象,而是创建一个包装器,以便您可以执行所需的操作。 结果是一个普通对象,没有方法,并且可以像访问任何对象一样进行访问。

我做的事

如果您希望1个localStorage属性具有魔力:

var prop = ObjectStorage(localStorage, 'prop');

如果您需要几个:

var storage = ObjectStorage(localStorage, ['prop', 'more', 'props']);

你所做的一切,以prop ,或内部的对象storage将被自动保存到localStorage 。 您总是在玩一个真实的对象,因此您可以执行以下操作:

storage.data.list.push('more data');
storage.another.list.splice(1, 2, {another: 'object'});

并且跟踪对象的每个新对象都会被自动跟踪。

很大的缺点:它取决于Object.observe()因此它对浏览器的支持非常有限。 而且看起来它不会很快就用于Firefox或Edge。


#13楼

看看这个

假设您有一个称为电影的以下数组:

var movies = ["Reservoir Dogs", "Pulp Fiction", "Jackie Brown", 
              "Kill Bill", "Death Proof", "Inglourious Basterds"];

使用字符串化功能,可以使用以下语法将电影数组转换为字符串:

localStorage.setItem("quentinTarantino", JSON.stringify(movies));

请注意,我的数据存储在名为quentinTarantino的密钥下。

检索数据

var retrievedData = localStorage.getItem("quentinTarantino");

要将字符串从字符串转换回对象,请使用JSON解析函数:

var movies2 = JSON.parse(retrievedData);

您可以在电影上调用所有数组方法2


#14楼

要存储一个对象,您可以写一个字母,用它来将一个对象从字符串传送到一个对象(可能没有意义)。 例如

var obj = {a: "lol", b: "A", c: "hello world"};
function saveObj (key){
    var j = "";
    for(var i in obj){
        j += (i+"|"+obj[i]+"~");
    }
    localStorage.setItem(key, j);
} // Saving Method
function getObj (key){
    var j = {};
    var k = localStorage.getItem(key).split("~");
    for(var l in k){
        var m = k[l].split("|");
        j[m[0]] = m[1];
    }
    return j;
}
saveObj("obj"); // undefined
getObj("obj"); // {a: "lol", b: "A", c: "hello world"}

如果使用用于拆分对象的字母,此技术将引起一些故障,这也是非常实验性的。


#15楼

遍历本地存储

var retrievedData = localStorage.getItem("MyCart");                 

retrievedData.forEach(function (item) {
   console.log(item.itemid);
});

#16楼

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

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

持久功能

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


#17楼

我修改了投票最多的答案之一。 我喜欢单一功能而不是2(如果不需要)。

Storage.prototype.object = function(key, val) {
    if ( typeof val === "undefined" ) {
        var value = this.getItem(key);
        return value ? JSON.parse(value) : null;
    } else {
        this.setItem(key, JSON.stringify(val));
    }
}

localStorage.object("test", {a : 1}); //set value
localStorage.object("test"); //get value

另外,如果未设置任何值,则返回null而不是falsefalse具有某些含义, null没有含义。


#18楼

您可以使用ejson将对象存储为字符串。

EJSON是JSON的扩展,以支持更多类型。 它支持所有JSON安全类型,以及:

所有EJSON序列化也是有效的JSON。 例如,带有日期和二进制缓冲区的对象将在EJSON中序列化为:

 { "d": {"$date": 1358205756553}, "b": {"$binary": "c3VyZS4="} } 

这是我使用ejson的localStorage包装器

https://github.com/UziTech/storage.js

我在包装器中添加了一些类型,包括正则表达式和函数


#19楼

我制作了另一个仅包含20行代码的简约包装器,以允许像应有的方式使用它:

localStorage.set('myKey',{a:[1,2,5], b: 'ok'});
localStorage.has('myKey');   // --> true
localStorage.get('myKey');   // --> {a:[1,2,5], b: 'ok'}
localStorage.keys();         // --> ['myKey']
localStorage.remove('myKey');

https://github.com/zevero/simpleWebstorage


#20楼

您可以使用localDataStorage透明地存储javascript数据类型(数组,布尔值,日期,浮点数,整数,字符串和对象)。 它还提供轻量级的数据混淆,自动压缩字符串,方便按键(名称)查询和按(键)值查询,并通过在键之前添加前缀来帮助在同一域中强制执行分段共享存储。

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

例子:

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

如您所见,原始值受到尊重。


#21楼

扩展存储对象是一个了不起的解决方案。 对于我的API,我为localStorage创建了一个Facade,然后在设置和获取时检查它是否为对象。

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

#22楼

对于愿意设置和获取键入属性的Typescript用户:

/**
 * Silly wrapper to be able to type the storage keys
 */
export class TypedStorage<T> {

    public removeItem(key: keyof T): void {
        localStorage.removeItem(key);
    }

    public getItem<K extends keyof T>(key: K): T[K] | null {
        const data: string | null =  localStorage.getItem(key);
        return JSON.parse(data);
    }

    public setItem<K extends keyof T>(key: K, value: T[K]): void {
        const data: string = JSON.stringify(value);
        localStorage.setItem(key, data);
    }
}

用法示例

// write an interface for the storage
interface MyStore {
   age: number,
   name: string,
   address: {city:string}
}

const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();

storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok

const address: {city:string} = storage.getItem("address");

#23楼

更好的是,将函数设置为localStorage的 setter和getter,这样,您将可以更好地控制并且不必重复JSON解析等等。 它甚至可以顺利处理您的(“”)空字符串键/数据大小写。

function setItemInStorage(dataKey, data){
    localStorage.setItem(dataKey, JSON.stringify(data));
}

function getItemFromStorage(dataKey){
    var data = localStorage.getItem(dataKey);
    return data? JSON.parse(data): null ;
}

setItemInStorage('user', { name:'tony stark' });
getItemFromStorage('user'); /* return {name:'tony stark'} */

#24楼

从理论上讲,可以存储具有以下功能的对象:

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

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


#25楼

Localstorage只能存储键和值都必须为string的键-值对。 但是,您可以通过将对象序列化为JSON字符串,然后在检索它们时将它们反序列化为JS对象来存储对象。

例如:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// JSON.stringify turns a JS object into a JSON string, thus we can store it
localStorage.setItem('testObject', JSON.stringify(testObject));

// After we recieve a JSON string we can parse it into a JS object using JSON.parse
var jsObject = JSON.parse(localStorage.getItem('testObject')); 

请注意,这将删除已建立的原型链。 最好通过示例显示:

 function testObject () { this.one = 1; this.two = 2; this.three = 3; } testObject.prototype.hi = 'hi'; var testObject1 = new testObject(); // logs the string hi, derived from prototype console.log(testObject1.hi); // the prototype of testObject1 is testObject.prototype console.log(Object.getPrototypeOf(testObject1)); // stringify and parse the js object, will result in a normal JS object var parsedObject = JSON.parse(JSON.stringify(testObject1)); // the newly created object now has Object.prototype as its prototype console.log(Object.getPrototypeOf(parsedObject) === Object.prototype); // no longer is testObject the prototype console.log(Object.getPrototypeOf(parsedObject) === testObject.prototype); // thus we cannot longer access the hi property since this was on the prototype console.log(parsedObject.hi); // undefined 


#26楼

我有这个JS对象 *我想将其存储在HTML5本地存储中

   todosList = [
    { id: 0, text: "My todo", finished: false },
    { id: 1, text: "My first todo", finished: false },
    { id: 2, text: "My second todo", finished: false },
    { id: 3, text: "My third todo", finished: false },
    { id: 4, text: "My 4 todo", finished: false },
    { id: 5, text: "My 5 todo", finished: false },
    { id: 6, text: "My 6 todo", finished: false },
    { id: 7, text: "My 7 todo", finished: false },
    { id: 8, text: "My 8 todo", finished: false },
    { id: 9, text: "My 9 todo", finished: false }
];

我可以在HTML5本地存储以这种方式, 存储这个由透过JSON.stringify

localStorage.setItem("todosObject", JSON.stringify(todosList));

现在,我可以通过JSON.parsing从本地存储获取此对象。

todosList1 = JSON.parse(localStorage.getItem("todosObject"));
console.log(todosList1);

#27楼

您还可以覆盖默认的Storage setItem(key,value)getItem(key)方法,以像处理任何其他数据类型一样处理对象/数组。 这样,您可以像往常一样简单地调用localStorage.setItem(key,value)localStorage.getItem(key)

我没有对此进行广泛的测试,但是对于我一直在修补的一个小项目,它似乎可以正常工作。

Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function(key, value)
{
  this._setItem(key, JSON.stringify(value));
}

Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype.getItem = function(key)
{  
  try
  {
    return JSON.parse(this._getItem(key));
  }
  catch(e)
  {
    return this._getItem(key);
  }
}

#28楼

我找到了一种使其与具有循环引用的对象一起使用的方法。

让我们用循环引用创建一个对象。

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”的意思是parse(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 = (function(){ "use strict"; var ignore = [Boolean, Date, Number, RegExp, String]; function primitive(item){ if (typeof item === 'object'){ if (item === null) { return true; } for (var i=0; i<ignore.length; i++){ if (item instanceof ignore[i]) { return true; } } return false; } else { return true; } } function infant(value){ return Array.isArray(value) ? [] : {}; } function decycleIntoForest(object, replacer) { if (typeof replacer !== 'function'){ replacer = function(x){ return x; } } object = replacer(object); if (primitive(object)) return object; var objects = [object]; var forest = [infant(object)]; var bucket = new WeakMap(); // bucket = inverse of objects bucket.set(object, 0); function addToBucket(obj){ var result = objects.length; objects.push(obj); bucket.set(obj, result); return result; } function isInBucket(obj){ return bucket.has(obj); } function processNode(source, target){ Object.keys(source).forEach(function(key){ var value = replacer(source[key]); if (primitive(value)){ target[key] = {value: value}; } else { var ptr; if (isInBucket(value)){ ptr = bucket.get(value); } else { ptr = addToBucket(value); var newTree = infant(value); forest.push(newTree); processNode(value, newTree); } target[key] = {pointer: ptr}; } }); } processNode(object, forest[0]); return forest; }; function deForestIntoCycle(forest) { var objects = []; var objectRequested = []; var todo = []; function processTree(idx) { if (idx in objects) return objects[idx]; if (objectRequested[idx]) return null; objectRequested[idx] = true; var tree = forest[idx]; var node = Array.isArray(tree) ? [] : {}; for (var key in tree) { var o = tree[key]; if ('pointer' in o) { var ptr = o.pointer; var value = processTree(ptr); if (value === null) { todo.push({ node: node, key: key, idx: ptr }); } else { node[key] = value; } } else { if ('value' in o) { node[key] = o.value; } else { throw new Error('unexpected') } } } objects[idx] = node; return node; } var result = processTree(0); for (var i = 0; i < todo.length; i++) { var item = todo[i]; item.node[item.key] = objects[item.idx]; } return result; }; var console = { log: function(x){ var the = document.getElementById('the'); the.textContent = the.textContent + '\\n' + x; }, delimiter: function(){ var the = document.getElementById('the'); the.textContent = the.textContent + '\\n*******************************************'; } } function logCyclicObjectToConsole(root) { var cycleFree = decycleIntoForest(root); var shown = cycleFree.map(function(tree, idx) { return false; }); var indentIncrement = 4; function showItem(nodeSlot, indent, label) { var leadingSpaces = ' '.repeat(indent); var leadingSpacesPlus = ' '.repeat(indent + indentIncrement); if (shown[nodeSlot]) { console.log(leadingSpaces + label + ' ... see above (object #' + nodeSlot + ')'); } else { console.log(leadingSpaces + label + ' object#' + nodeSlot); var tree = cycleFree[nodeSlot]; shown[nodeSlot] = true; Object.keys(tree).forEach(function(key) { var entry = tree[key]; if ('value' in entry) { console.log(leadingSpacesPlus + key + ": " + entry.value); } else { if ('pointer' in entry) { showItem(entry.pointer, indent + indentIncrement, key); } } }); } } console.delimiter(); showItem(0, 0, 'root'); }; function stringify(obj){ return JSON.stringify(decycleIntoForest(obj)); } function parse(str){ return deForestIntoCycle(JSON.parse(str)); } var CYCLICJSON = { decycleIntoForest: decycleIntoForest, deForestIntoCycle : deForestIntoCycle, logCyclicObjectToConsole: logCyclicObjectToConsole, stringify : stringify, parse : parse } function setObject(name, object){ var str = stringify(object); localStorage.setItem(name, str); } function getObject(name){ var str = localStorage.getItem(name); if (str===null) return null; return parse(str); } return { CYCLICJSON : CYCLICJSON, setObject : setObject, getObject : getObject } })(); obj = { L: { L: { v: 'lorem' }, R: { v: 'ipsum' } }, R: { L: { v: 'dolor' }, R: { L: { v: 'sit' }, R: { v: 'amet' } } } } obj.RLuncle = obj.L; obj.RRuncle = obj.L; obj.RRLuncle = obj.RL; obj.RRRuncle = obj.RL; obj.LLuncle = obj.R; obj.LRuncle = obj.R; // LOCALSTORAGE.setObject('latinUncles', obj) // recovered = LOCALSTORAGE.getObject('latinUncles') // localStorage not available inside fiddle ): LOCALSTORAGE.CYCLICJSON.logCyclicObjectToConsole(obj) putIntoLS = LOCALSTORAGE.CYCLICJSON.stringify(obj); recovered = LOCALSTORAGE.CYCLICJSON.parse(putIntoLS); LOCALSTORAGE.CYCLICJSON.logCyclicObjectToConsole(recovered); var the = document.getElementById('the'); the.textContent = the.textContent + '\\n\\n' + JSON.stringify( [ obj.LLv === recovered.LLv, obj.LRv === recovered.LRv, obj.RLv === recovered.RLv, obj.RRLv === recovered.RRLv, obj.RRRv === recovered.RRRv, obj.RLuncle === obj.L, obj.RRuncle === obj.L, obj.RRLuncle === obj.RL, obj.RRRuncle === obj.RL, obj.LLuncle === obj.R, obj.LRuncle === obj.R, recovered.RLuncle === recovered.L, recovered.RRuncle === recovered.L, recovered.RRLuncle === recovered.RL, recovered.RRRuncle === recovered.RL, recovered.LLuncle === recovered.R, recovered.LRuncle === recovered.R ] ) 
 <pre id='the'></pre> 


#29楼

从答案看,似乎有很多方法可以存储JavaScript对象。

您可以设置关键字: store ,语言: javascript ,排序方式: 'Most Star'

尝试使用此GitHub链接,您将在顶部获得当前最多的选择。


#30楼

有一个很棒的库,其中包含许多解决方案,因此它甚至支持名为jStorage的旧版浏览器。

您可以设置一个对象

$.jStorage.set(key, value)

并轻松检索

value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值