eval返回未定义,浏览器返回结果 [英] eval returning undefined, browser returning a result

查看:208
本文介绍了eval返回未定义,浏览器返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的javascript字符串:

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

如果我将字符串保存到变量中并求值,它将返回未定义的状态:

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

但是,如果我将字符串粘贴到Chrome JS控制台中,它将按预期返回:

"hello"

任何原因为何eval都将返回未定义,并且JS控制台如何完成这一壮举?

谢谢!

解决方案

表达式"h" + "e" + "l" + ("foo", "bar", "l") + ("abc", "def", "o")的计算结果为字符串"hello".

如果将其粘贴到Chrome控制台中,则会得到其评估结果.

如果将其传递给eval,则表达式的计算结果为字符串"hello",然后eval接受该字符串,并计算为未定义的变量名 hello. /p>

如果只想将"hello"放入变量中,则不要使用eval,请使用赋值.

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

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!

解决方案

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);

这篇关于eval返回未定义,浏览器返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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