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

查看:147
本文介绍了为什么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'); }()

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

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天全站免登陆