最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get last return value - Stack Overflow

programmeradmin0浏览0评论

In nodeJS terminal, I can enter this expression and have as a return 'true':

> var x = true; x;
true

How can I capture this return value in a variable, without changing the expression?

The following is not working:

> var y = (var x = true; x)
SyntaxError: Unexpected token var

In nodeJS terminal, I can enter this expression and have as a return 'true':

> var x = true; x;
true

How can I capture this return value in a variable, without changing the expression?

The following is not working:

> var y = (var x = true; x)
SyntaxError: Unexpected token var
Share Improve this question asked Mar 25, 2015 at 14:43 simon.denelsimon.denel 7986 silver badges23 bronze badges 7
  • 3 You haven't entered an expression - you've entered two statements – James Thorpe Commented Mar 25, 2015 at 14:45
  • using eval ? :) This question is unclear, you mean you want to have some chars before and some after ? Why ? – Denys Séguret Commented Mar 25, 2015 at 14:45
  • @dystroy: I noticed eval is working. I would like the exact behavior of eval, but without using it (the expression is not a string, it's already code). I fear eval would give me a performance problem (code is in a deep loop) – simon.denel Commented Mar 25, 2015 at 14:47
  • 7 Is it a quiz question ? It looks so far from anything useful. It might be a XY problem – Denys Séguret Commented Mar 25, 2015 at 14:48
  • @dystroy: no it is not. My problem is real. – simon.denel Commented Mar 25, 2015 at 14:51
 |  Show 2 more comments

2 Answers 2

Reset to default 21

In node REPL, you can just use _ :

> var x = true; x;
true
> var y = _
undefined
> y
true

You can't use a statement as an expression.

x = true is an expression, and x is also an expression. var x = true is not an expression, it's a statement.

To use the expression you would declare the variable x first. The value of an assignment expression is the value that was assigned, so you don't need to put x; after the assignment (which helps as that makes it a statement):

var x; var y = (x = true);
发布评论

评论列表(0)

  1. 暂无评论