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

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

问题描述

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

var count = 0;而(计数<10){控制台日志(计数);计数++;}

控制台日志的输出是 0,1,2...9.(如预期).然而,还有一个返回到控制台的数字:

<- 9

这个返回值从何而来?

我假设这是count++ 表达式 的返回值.但是为什么不是每个循环都返回值?

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

解决方案

Read-eval-print-loops (REPL) 就像浏览器控制台一样显示代码生成的最后结果.有点令人惊讶的是,JavaScript while 循环和块有结果.对于块,它是块中最后一条语句的结果.对于 while 语句,它是附加到 while 的语句的最后一次迭代的结果(在你的例子中是一个块).

这里有一个更简单的例子,只有一个块:

{1 + 1;3 + 3;}

在像浏览器控制台这样的 REPL 中,上面会显示 6,因为它是一个包含两个 ExpressionStatements.第一个ExpressionStatement的结果是2(那个结果被扔掉),第二个的结果是6,所以block的结果是6.这就是规范中涵盖:

<块引用>

  1. blockValue 成为评估 StatementList 的结果.
  2. 将运行执行上下文的 LexicalEnvironment 设置为 oldEnv.
  3. 返回blockValue.

while 循环结果是 此处介绍.

<块引用>

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

不,无法在代码中访问这些结果.例如,你不能做 var x = while (count < 10 { count++; }); 或类似的.您必须在循环/块/等内部捕获您想要的结果,并将其分配给一个变量或类似的.或者(我建议这样做),使用 eval 作为 Alin 点出.

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++;
}

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

Where does this return value come from?

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?

解决方案

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

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. Let blockValue be the result of evaluating StatementList.
  2. Set the running execution context’s LexicalEnvironment to oldEnv.
  3. Return blockValue.

while loop results are covered here.

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

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天全站免登陆