【问题标题】:if statements in an arrow function [duplicate]箭头函数中的 if 语句 [重复]
【发布时间】:2018-05-26 23:08:47
【问题描述】:

storyWords.filter(word => if (unnecessaryWords.includes(word)){
  continue;
}
else{
  betterWords.push(word);
}) ;                 

我不断收到错误“Unexpected token if”,我想知道当您使用箭头函数时,if 语句的语法是否与常规函数中的不同。

【问题讨论】:

  • 您不能在只允许使用表达式的上下文中使用语句或声明。使用带有{} 的箭头函数,以便您可以在其中放置语句。
  • 这不是过滤器的使用方式..应该是betterWords = storyWords.filter(word => !( unnecessaryWords.includes(word) ));

标签: javascript arrays ecmascript-6


【解决方案1】:

如果您在箭头函数中有 statement(中断、继续、if...else 或 switch),则需要使用花括号:{ }。

箭头函数可以有“简洁体”或通常的“块体”。

在简洁的正文中,仅指定了一个表达式,该表达式成为显式返回值。在块体中,必须使用显式的 return 语句。

-MDN web docs

所以写:

storyWords.filter(word => {

  if (unnecessaryWords.includes(word)) {
    continue;
  } else {
    betterWords.push(word);
  }

});

【讨论】:

  • 正如您自己引用的文档:在块体中,您必须使用显式的 return 语句。 continue 关键字在任何循环外都有效吗?
  • @Quasimodo'sclone,我认为它在循环外无效,MDN 读取: continue 语句终止当前或标记循环的当前迭代中语句的执行,并且在下一次迭代中继续执行循环。
  • 迭代在filter方法中完成。在回调函数的上下文中没有循环。 filter 需要一个 bool 返回值。
猜你喜欢
  • 2020-10-19
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 2022-11-08
  • 2018-06-15
  • 2021-04-22
  • 1970-01-01
  • 2016-03-25
相关资源
最近更新 更多