【发布时间】:2015-08-12 14:07:41
【问题描述】:
我有对象用 JSON.stringify() 'stringify'd,然后用 localstorage.setItem() 保存,然后用 localstorage.getItem() 检索,然后用 JSON.parse() 解析,最后被返回到程序中使用的对象数组中。这是我的代码:
var exampleObjects = [];
function objectExample() {
this.exampleFunction = function() {
return this.otherObjectCreatedElsewhere.value;
}
this.otherObjectCreatedElsewhere;
}
function main() {
exampleObjects[ 0 ] = new objectExample();
exampleObjects[ 0 ].otherObjectCreatedElsewhere = otherObjectCreatedElsewhere;
exampleObjects[ 0 ].exampleFunction(); //Works
var save0 = JSON.stringify( exampleObjects[ 0 ] );
localstorage.setItem( 'key', save0 );
save0 = localstorage.getItem( 'key' );
exampleObjects[ 0 ] = JSON.parse( save0 );
exampleObjects[ 0 ].exampleFunction(); //No longer works, instead throws error exampleObjects[ 0 ].exampleFunction is not a function
}
main();
现在我已经使用 reviver 方法查找了 JSON.parse,但我终生无法弄清楚。我没有上过学,这只是我的一个爱好,但我已经培养了几年了。我真的很喜欢它,但这样的时刻令人沮丧。
编辑
我已经通过 cloudfeet 的宝贵建议解决了这个问题。基本上我从保存的 JSON 字符串中取出对象,然后将它们解析为对象,然后创建一个新对象并重新分配所有丰富的属性。
再次感谢!
【问题讨论】:
-
函数在 JSON 语法中无效。请参阅json.org — 您可以拥有字符串、数字、对象、数组、
true、false和null,但不能拥有函数。
标签: javascript json