Javascript while循环返回值 [英] Javascript while loop return value

查看:185
本文介绍了Javascript while循环返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Javascript中有一个关于while循环的简单问题。
当我在浏览器控制台中运行这个简单循环时:

I have a simple question regarding while loop in Javascript. When I run this simple loop in browser console:

var count = 0;
while (count < 10) {
    console.log(count);
    count++;
}

控制台日志的输出为0,1, 2 ... 9。 (正如预期的那样)
但是还有一个号码返回到控制台:

The output to console log is 0,1,2...9. (as expected). However there is one more number which is returned to the console:

<- 9

这个返回值来自哪里?

我假设这个是 count ++ expression 的返回值。但是为什么每个循环都没有返回值?

I assume this is the return value of count++ expression. But why is the value not returned by every single loop?

是否有可能以某种方式将返回的值捕获到变量?

Is it possible to somehow catch that returned value to a variable?

推荐答案

像浏览器控制台这样的读取eval-print-loops(REPL)显示代码生成的最后结果。有点令人惊讶的是,JavaScript 循环和块有结果。对于块,它是块中最后一个语句的结果。对于语句,它是附加到的语句的最后一次迭代的结果,而(在你的情况下是一个块) )。

Read-eval-print-loops (REPLs) like browser consoles show the last result that the code generated. Somewhat surprisingly, JavaScript while loops and blocks have a result. For blocks, it's the result of the last statement in the block. For while statements, it's the result of the last iteration of the statement attached to the while (a block in your case).

这是一个只有一个块的简单示例:

Here's a simpler example with just a block:

{1 + 1; 3 + 3;}

在像浏览器控制台这样的REPL中,上面会显示6,因为这是一个包含两个 ExpressionStatements <的块/ EM> 。第一个ExpressionStatement的结果是2(结果被抛弃),第二个的结果是6,所以块的结果是6.这是规范

In a REPL like the browser console, the above will show you 6, because it's a block containing two ExpressionStatements. The result of the first ExpressionStatement is 2 (that result is thrown away), and the result of the second one is 6, so the result of the block is 6. This is covered in the specification:



  1. blockValue 成为评估 StatementList 的结果。

  2. 将正在运行的执行上下文的LexicalEnvironment设置为oldEnv。

  3. 返回 blockValue

  1. Let blockValue be the result of evaluating StatementList.
  2. Set the running execution context’s LexicalEnvironment to oldEnv.
  3. Return blockValue.


循环结果是此处涵盖


是否有可能以某种方式将返回的值捕获到变量?

Is it possible to somehow catch that returned value to a variable?

不,这些[R代码中无法访问结果。例如,你不能做 var x = while(count< 10 {count ++;}); 或类似的。您必须捕获循环/块/等中的结果,将其分配给变量或类似变量。或者(我暗示这一点),使用 eval Alin指出

No, these results are not accessible in the code. E.g., you can't do var x = while (count < 10 { count++; }); or similar. You'd have to capture the result you want inside the loop/block/etc., assigning it to a variable or similar. Or (and I'm not suggesting this), use eval as Alin points out.

这篇关于Javascript while循环返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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