为什么 eval 在这里失败?

发布于 2024-10-04 23:42:09 字数 146 浏览 0 评论 0原文

0001: response
$[0] = [string] "{\"code\":200,\"id\":121}"
0001: eval(response)
SyntaxError: invalid label

有人知道吗?

0001: response
$[0] = [string] "{\"code\":200,\"id\":121}"
0001: eval(response)
SyntaxError: invalid label

Anyone knows?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

沫雨熙 2024-10-11 23:42:09

您必须将其包装在 () 中才能触发表达式求值,如下所示:

eval("(" + response + ")")

您可以在这里测试一下


虽然更好的方法是原生 JSON 处理:

var result = JSON.parse(response);

只需包含 json2.js 对于旧版浏览器(< IE8 ) 支持,调用是相同的...它只是添加全局 JSON 对象(如果丢失)。

You have to wrap it in () to trigger expression evaluation, like this:

eval("(" + response + ")")

You can test it out here.


Though a better method is native JSON handling:

var result = JSON.parse(response);

Just include json2.js for older browser (< IE8) support, the call is the same...it just adds the global JSON object if it's missing.

半透明的墙 2024-10-11 23:42:09

您需要将 JSON 字符串括在括号中。

否则,{ ... } 会被解释为可执行语句块,但事实并非如此。

通过将其括在括号中,可以强制解释器将其解释为表达式。

You need to wrap the JSON string in parentheses.

Otherwise, the { ... } is interpreted as a block of executable statements, which it isn't.

By surrounding it in parentheses, you force the interpreter to interpret it as an expression.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文