为什么jquery local拷贝为localStorage不起作用?

时间:2015-05-04 18:29:10

标签: javascript jquery copy deep-copy

我在localStorage中获得的是[object Object],但对于javascript中的其他变量,它确实有效。

示例代码:

var some_hash = {
"key1":"value1",
"key2": "value2",
"key3" : [{
"key3a": "value3a"}]


}

var deep_copy = $.extend(true, {}, some_hash)
console.log(deep_copy)
Object {key1: "value1", key2: "value2", key3: Array[1]}

localStorage["help"] = $.extend(true, {}, some_hash)
console.log(localStorage["help"])
[object Object]

为什么?任何解决方法?

1 个答案:

答案 0 :(得分:3)

localStorage只将值存储为字符串,而不是对象。

尝试使用JSON.stringify和JSON.parse:

 var deep_copy = JSON.stringify($.extend(true, {}, some_hash));
 console.log(JSON.parse(deep_copy));

另见: Storing Objects in HTML5 localStorage