简体   繁体   中英

eval is not working in IE8

I could not find reason why this small code snippet is not working in IE8,

var a = {"ff": "test"};
eval('('+a+')');

I am getting error as

']' expected".

When concatenating the object a to form part of the eval'd string, a.toString() is called, which will output [object Object] . What you want is for {"ff": "test"}; to be concatenated into the eval'd string, so you'll need to use JSON.stringify() to achieve that.

Try this:

eval('('+JSON.stringify(a)+')');

Or alternatively you could just put quotes around the object declaration on the first line:

var a = '{"ff": "test"}';
var a = {"ff": "test"};
eval('('+a+')');

This is evaluated as:

([object Object])

And that's obviously not valid JavaScript. If you want to preserve a data structure, you can use JSON.stringify() and JSON.parse() .

var a_to_json = JSON.stringify(a);
var a_from_json = JSON.parse(a_to_json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM