我的目标是将对象转换为文本形式,可以使用localStorage进行存储,然后使用 eval() 检索并转换回其原始对象形式。我编写了一个名为 uneval() 的函数来转换为文本,如下所示:
function uneval(obj){
// Convert object to a string that can be evaluated with eval() to its original
if(obj===null)return 'null';
if(typeof obj === 'number' || typeof obj === 'boolean')return ''+obj;
if(typeof obj === 'string')return '"'+obj+'"';
if(Object.prototype.toString.call(obj) === '[object Array]')
{ var str = '[', i=0, l=obj.length;
for(i;i<l;i++)str+= (i==0?'':',') + uneval(obj[i]);
return str+']';
}
if(typeof obj === 'object')
{ var str='({', i;
for (i in obj)str+= (2==str.length?'':',') + i + ':' + uneval(obj[i]);
return str+='})';
}
if(typeof obj === 'function')return '(' + obj.toString() + ')';
return '';}
[编辑 1:{} 中的对象需要使用 eval() 成功转换括号]
[编辑 2:修改功能代码以在功能代码字符串周围放置括号]
[编辑 3:更改为用于递归避免 arguments.callee 的命名函数]
[编辑 4:处理空值]
请注意,此函数保留嵌套结构。它可以正常工作(至少在 Google Chrome 和 MS IE8 中),除非对象或对象的项是函数。我通过将字符串形式的函数分配给一个不太可能的变量(如“_=”)找到了一种解决方法。这就是工作。没有它,我会从 eval() 中得到一个语法错误。谁能解释一下为什么会这样?
顺便说一句,我可以通过在 _ 本地化的覆盖函数中调用 eval() 来避免使用 _ 作为变量发生冲突的可能性很小。