在JavaScript中使用块的返回值 [英] Using a block's return value in JavaScript

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

问题描述

在我测试过的很多浏览器中,JavaScript块实际上返回了一个值。您可以在任何控制台中测试它:

On a lot of browsers I've tested, JavaScript blocks actually return a value. You can test it out in any console:

for(var i = 0; i < 10; i++) {
    var sqrt = Math.sqrt(i);
    if(Math.floor(sqrt) === sqrt) {
        i;
    }
}

返回值是最后一个方格数,就是9!但是因为它不是我想的表达式,你不能这样做:

The "return" value is the last square number, that is, 9! But since it isn't an expression I suppose, you can't do this:

for(var i = 0; i < 10; i++) {
    ...
} + 5

这不起作用。它提供 + 5 ,或 5 ,当然,因为它是一个单独的声明。将循环放在括号中显然会失败,如果一个块在括号中(例如({f(); r}) - 不起作用)它被视为一个对象并抛出语法错误。

That doesn't work. It gives + 5, or 5, of course, because it's a separate statement. Putting the loop in parentheses obviously fails, and if a block is in parentheses (e.g. ({f(); r}) - doesn't work) it's treated as an object and throws a syntax error.

利用返回值的一种方法是使用 eval

One way to take advantage of the return value, as such, is to use eval:

eval('for(var i = 0; i < 10; i++) {var sqrt = Math.sqrt(i);if(Math.floor(sqrt) === sqrt) {i;}}') + 5; // 14

但是如果 eval 是唯一的解决方案。有没有办法使用块的结果值而不使用我缺少的 eval ?我非常喜欢这个功能:)

But I'm obviously not going to want to use that if eval is the only solution. Is there a way to use a block's resultant value without using eval that I'm missing? I really like this feature :)

推荐答案

在JavaScript中,语句返回Completion类型的值(不是语言类型,但规范类型)。

In JavaScript, statements return values of the Completion type (which is not a language type, but a specification type).


完成类型用于解释语句的行为
中断继续返回抛出)执行
控制的非本地转移。完成类型的值是表单的三元组(类型
目标),其中类型正常中断继续返回
之一是任何ECMAScript语言值或目标
是任何ECMAScript标识符或为空

The Completion type is used to explain the behaviour of statements (break, continue, return and throw) that perform nonlocal transfers of control. Values of the Completion type are triples of the form (type, value, target), where type is one of normal, break, continue, return, or throw, value is any ECMAScript language value or empty, and target is any ECMAScript identifier or empty.

来源: http://es5.github.com/x8.html#x8.9

所以, eval()评估作为源文本传入的程序。该程序(与任何JavaScript程序一样)返回Completion值。此完成值中的第二项(值项)由 eval()调用返回。

So, eval() evaluates the program that has been passed in as source text. That program (like any JavaScript program) returns a Completion value. The second item in this Completion value (the "value" item) is returned by the eval() invocation.

因此,使用 eval ,您可以检索JavaScript程序的完成值。我不知道有任何其他方法可以实现这一目标......

So, with eval you are able to retrieve the completion value of an JavaScript program. I am not aware of any other method to accomplish this...

这篇关于在JavaScript中使用块的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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