为什么 JavaScript 的 eval 需要括号来评估 JSON 数据? [英] Why does JavaScript's eval need parentheses to eval JSON data?

查看:28
本文介绍了为什么 JavaScript 的 eval 需要括号来评估 JSON 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经(艰难地)了解到我需要在 JSON 数据周围添加括号,如下所示:

I've learned (the hard way) that I need to add parentheses around JSON data, like this:

stuff = eval('(' + data_from_the_wire + ')');
// where data_from_the_wire was, for example {"text": "hello"}

(至少在 Firefox 3 中).

(In Firefox 3, at least).

这背后的原因是什么?我讨厌在不了解幕后内容的情况下编写代码.

What's the reason behind this? I hate writing code without understanding what´s behind the hood.

推荐答案

data_from_the_wire 周围加上括号实际上相当于

Putting the parentheses around data_from_the_wire is effectively equivalent to

stuff = eval('return ' + data_from_the_wire + ';');

如果您要在不带括号的情况下进行 eval,则将评估代码,如果您在其中确实有任何命名函数,则这些函数将被定义,但不会返回.

If you were to eval without the parentheses, then the code would be evaluated, and if you did have any named functions inside it those would be defined, but not returned.

以在创建函数时调用函数的能力为例:

Take as an example the ability to call a function just as it han been created:

(function() { alert('whoot'); })()

将调用刚刚定义的函数.但是,以下方法不起作用:

Will call the function that has just been defined. The following, however, does not work:

function() { alert('whoot'); }()

因此我们看到括号有效地将 then 代码转换为返回的表达式,而不仅仅是要运行的代码.

So we see that the parentheses effectively turn then code into an expression that returns, rather than just code to run.

这篇关于为什么 JavaScript 的 eval 需要括号来评估 JSON 数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆