eval returning undefined, browser returning a result

守給你的承諾、 提交于 2019-12-12 05:19:02

问题


I've got a javascript string such as the following:

"h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o")

If I save the string to a variable and eval it, it returns as undefined:

var str = "h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o");
var x = eval (str);
console.log(x) // undefined

However, if I paste the string into the Chrome JS console, it returns as expected:

"hello"

Any reason why eval would return undefined, and how is the JS console accomplishing the feat?

Thanks!


回答1:


The expression "h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o") evaluates as the string "hello".

If you paste that into the Chrome console, then you get what it evaluates to displayed.

If you pass it to eval then the expression evaluates to the string "hello" and then eval takes that string and evaluates to the variable name hello which isn't defined.

If you just want to get "hello" into a variable, then don't use eval, use an assignment.

var x = "h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o");
console.log(x);



回答2:


When you paste the string into the console, it immediately evaluates the operations you have defined, thus you get the proper

"hello"

result. When you go to eval, however, you should see "ReferenceError: hello is not defined." This is because the string operations have again been immediately resolved, so your call to eval becomes

eval('hello')

which is meaningless.



来源:https://stackoverflow.com/questions/35639254/eval-returning-undefined-browser-returning-a-result

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