简体   繁体   English

为什么JS eval()仅返回对象的值

[英]Why does JS eval() return only the value of an object

If I do this: 如果我这样做:

var x = eval('{a:"b"});
console.log(x); // -> "b"

all I get is the value in the object ("b"), not the key/property, or the whole object itself, which is weird. 我得到的只是对象(“b”)中的值,而不是键/属性,或整个对象本身,这很奇怪。

but when I do this: 但是当我这样做时:

var x = eval('(function self(){return {a:"b"}})()');
console.log('x'); //  -> {a:'b'}

now it seems to give me what I would expect, the whole object. 现在它似乎给了我所期望的整个对象。 But why is this? 但为什么会这样呢? Why do I need to wrap it in a (self-executing) function? 为什么我需要将它包装在(自执行)函数中?

I am thinking of using eval to create some objects from strings, but need to know better how this works. 我正在考虑使用eval从字符串创建一些对象,但需要更好地了解它是如何工作的。

That's because {a:"b"} statement as-is represents the following: 这是因为{a:"b"}语句as-is代表以下内容:

  1. A code block delimited by { ... } { ... }分隔的代码
  2. A label a: 标签 a:
  3. A string literal "b" 字符串文字"b"

The latter being the only expression produces the result. 后者是唯一产生结果的表达式。

And the same in the AST explorer: https://astexplorer.net/#/gist/909bebf... AST浏览器中也是如此: https://astexplorer.net /#/ gist / 909bebf ...

To return an object you need to turn it into an expression first, like: wrap it in parentheses: eval('({a:"b"})') 要返回一个对象,首先需要将其转换为表达式,如:括在括号中: eval('({a:"b"})')

But the whole idea of "I am thinking of using eval to create some objects from strings" sounds suspicious. 但是“我正在考虑使用eval从字符串创建一些对象”的整个想法听起来很可疑。

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

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