私の目的は、オブジェクトを、たとえば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: 関数コード文字列を括弧で囲むように修正された関数コード]
[Edit 3: Changed to a named function for recursion avoiding arguments.callee]
[Edit 4: Handle null]
Note that this function retains nested structure. It works fine (at least in Google Chrome and MS IE8) except when the object, or an item of the object, is a function. I have found a workaround by making an assignment of the function in string form to an unlikely variable, as "_=". That does the job. Without that, I get a syntax error from eval(). Could anyone explain why that is the case, please?
By the way, I can avoid the small chance of a conflict using _ as a variable by calling eval() within a cover function in which _ is localised.