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

查看:22
本文介绍了在 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

那行不通.当然,它给出了 +55,因为它是一个单独的语句.将循环放在括号中显然会失败,如果一个块在括号中(例如 ({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).

Completion 类型用于解释语句的行为(break, continue, returnthrow) 执行非本地传输控制.Completion 类型的值是形式 (type,valuetarget),其中 typenormalbreak、<强>继续,返回,或 throwvalue 是任何 ECMAScript 语言值或 empty,以及 target是任何 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 值.此 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天全站免登陆