最近我在看Babel.js (previously 6to5)。这是ES6的转录器。它提供的一个有趣功能是将尾调用更改为循环。在示例中:
function factorial(n, acc = 1) {
"use strict";
if (n <= 1) return acc;
return factorial(n - 1, n * acc);
}
// Stack overflow in most implementations today,
// but safe on arbitrary inputs in eS6
factorial(100000)
Babel.js将其转换为:
"use strict";
var _temporalAssertDefined = function (val, name, undef) { if (val === undef) { throw new ReferenceError(name + " is not defined - temporal dead zone"); } return true; };
var _temporalUndefined = {};
function factorial(_x2) {
var _arguments = arguments;
var _again = true;
_function: while (_again) {
var n = _temporalUndefined;
var acc = _temporalUndefined;
_again = false;
var n = _x2;
n = acc = undefined;
n = _arguments[0] === undefined ? undefined : _arguments[0];
acc = _arguments[1] === undefined ? 1 : _arguments[1];
"use strict";
if ((_temporalAssertDefined(n, "n", _temporalUndefined) && n) <= 1) {
return _temporalAssertDefined(acc, "acc", _temporalUndefined) && acc;
}_arguments = [_x2 = (_temporalAssertDefined(n, "n", _temporalUndefined) && n) - 1, (_temporalAssertDefined(n, "n", _temporalUndefined) && n) * (_temporalAssertDefined(acc, "acc", _temporalUndefined) && acc)];
_again = true;
continue _function;
}
}
// Stack overflow in most implementations today,
// but safe on arbitrary inputs in eS6
factorial(100000);
我的问题是,我从未见过像_function: while(again)
这样的JavaScript语法。但它是有效的JavaScript!我尝试在Chrome devtools控制台中键入类似a: 1
的simliar代码,这是正确的。
有人能告诉我:
答案 0 :(得分:4)
它是一个标签,与continue,break一起使用:
my_label: while(true) {
while(true) {
break my_label;
}
}
console.log('did we survive?');
避免使用标签
标签在JavaScript中并不常用,因为它们使程序更难以阅读和理解。尽可能避免使用标签,并根据具体情况,更喜欢调用函数或抛出错误。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label