最近我在看Babel.js (先前为6至5)。这是一个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);我的问题是,我从未见过像JavaScript这样的语法。但是它是有效的JavaScript!我试图在Chrome控制台中键入类似a: 1的简单代码,这是正确的。
有人能告诉我:
发布于 2015-03-01 00:52:33
它是一个标签,与“继续”、“中断”一起使用:
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
https://stackoverflow.com/questions/28788785
复制相似问题