es6 arrow函数调试器语句 [英] es6 arrow functions debugger statement
问题描述
如果我有这样的功能:
param => params + 1
我需要放一个调试器
函数体内的语句。是这样添加括号:
and I need to put a debugger
statement inside the function's body. Is adding parenthesis like this:
param => { debugger; return params + 1 }
唯一选项?
推荐答案
来自 MDN 文章:
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
您可以看到无括号语法需要代码在箭头的右边是一个表达式,这是一个(不幸的)区别。
You can see that the brace-less syntax requires the code on the right of the arrow to be an expression, which is an (unfortunate) distinction made by the language itself.
由于调试器
是一个语句,在任何需要表达式的地方使用它都是语法错误。你可以解决这个问题的一个方法是在一个表达式中转换你的调试器语句,你可以用JavaScript来评估但不返回,例如:
Since debugger
is a statement, using it anywhere an expression is expected is a syntax error. One thing you could to to work around this is to transform your debugger statement in an expression which you trick JavaScript into evaluating but not returning, e.g.:
function debug(args) {
debugger;
return true;
}
params => debug() && params + 1
// or
params => console.log(params) || params + 1
这样做的方式是因为逻辑运算符在JavaScript中运行,这是真的:
The way this works is that because of the way logical operators function in JavaScript, this is true:
truthyA && B === B
falsyA || B === B
当链接逻辑运算符时,JavaScript从左到右评估子表达式然后行动取决于它们的布尔等价物。这就是为什么你有时会看到&&&
代替如果
语句:
When chaining logical operators, JavaScript evaluates sub-expressions left to right and then act depending on their boolean equivalent. That's why you'll sometimes see &&
used in place of if
statements:
if (smth) doStuff();
// is equivalent to:
smth && doStuff();
这篇关于es6 arrow函数调试器语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!