JavaScript eval(“{}”) return behavior?

这一生的挚爱 提交于 2019-12-13 13:35:53

问题


According to the ECMA-262 Specification, the following statements return 1:

eval("1;;;;;")
eval("1;{}")
eval("1;var a;")

Ensuring that:

The value of a StatementList is the value of the last value producing Statement in the StatementList.

Can you explain these different returns ?

eval("{}") // undefined
eval("var a={}; a;") // {}
eval("var a={};") // undefined

What is the difference between 1; and {}; ?


回答1:


Left alone, {} is interpreted as a block, not an object. It contains no statements, so does not affect the value of, say, eval("1;{}"). To force it to be interpreted as an object, you can use parentheses:

eval("1;({})"); // {}



回答2:


It looks to me like eval is interpreting {} as the delimiters of a code block, and therefore has no inherent value.



来源:https://stackoverflow.com/questions/10791202/javascript-eval-return-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!