简体   繁体   English

评估在IE8中不起作用

[英]eval is not working in IE8

I could not find reason why this small code snippet is not working in IE8, 我找不到这个小代码段无法在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] . 当连接对象a形成评估字符串的一部分时,将调用a.toString() ,这将输出[object Object] What you want is for {"ff": "test"}; 想要的是{"ff": "test"}; to be concatenated into the eval'd string, so you'll need to use JSON.stringify() to achieve that. 将其连接到评估字符串中,因此您需要使用JSON.stringify()来实现。

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. 那显然不是有效的JavaScript。 If you want to preserve a data structure, you can use JSON.stringify() and JSON.parse() . 如果要保留数据结构,可以使用JSON.stringify()JSON.parse()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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