Why isn't localStorage accepting my object?

This question already has an answer here:

  • Storing Objects in HTML5 localStorage 25 answers

  • Use JSON.stringify() to set JSON and JSON.parse() to convert JSON to a JavaScript object; localStorage expects a string to be set.


    From Using the Web Storage API:

    "Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do)."

    You cannot store a complex Object value in localStorage. Sorry.

    Instead, you should serialize your Object as a string [hint: JSON.stringify() ] and then after retrieving it parse from JSON string back to Object [hint: JSON.parse() ].


    localstorage限于字符串键/值对,在存储它之前使用JSON.stringify() ,在检索它之后使用JSON.parse()

    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));
    
    链接地址: http://www.djcxy.com/p/27934.html

    上一篇: 检索Web存储中的JSON数据无法正常工作

    下一篇: 为什么localStorage不接受我的对象?