0

私の目的は、オブジェクトを、たとえば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.

4

1 に答える 1

1

このコードでは:

var func = eval('function () {}');

eval文字列を関数式ではなく関数宣言として解析し、関数宣言を匿名にすることはできないため、構文エラーがスローされます。文字列が宣言ではなく関数式として解析されるようにするには、文字列の最初と最後に括弧を追加します。これらの親は、グループ化演算子として解析されます。次に、グループ化演算子の内容が式として解析されます。この場合は、関数式です。

var func = eval('(function () {})'); // doesn't throw

したがって、uneval関数で次のようにします。

if ( typeof obj === 'function' ) return '(' + obj.toString() + ')';
于 2013-02-15T18:06:16.687 に答える