Expression eval(“function(x) { return x*x}

2020-04-17 04:48发布

When I type something like this in node.js console:

var f = eval("function(x) { return x*x}");

It doesn't evaluate the expression and waits for me to type something else.

enter image description here

Why is this happening? Why can't I type another expression after this one?

标签: node.js eval
1条回答
够拽才男人
2楼-- · 2020-04-17 05:26
function(x) { return x*x}

is an error (type it in the console to check that), so Node's REPL waits for more.

If you want to build and assign the function, you must eval an expression, that is a statement returning a value. The usual solution is to close the function expression with parenthesis.

You may write

var f = eval("(function(x) { return x*x})");

or

var f = Function("x", "return x*x");

and of course

var f = function(x) { return x*x};

but I suppose you know this one.

查看更多
登录 后发表回答