【问题标题】:Line break within arrow function throws “Uncaught SyntaxError: Unexpected token `=>`”箭头函数内的换行符抛出“Uncaught SyntaxError: Unexpected token `=>`”
【发布时间】:2019-09-10 09:25:53
【问题描述】:

当我将 e 参数放在括号中并使用 ES6 箭头函数时,我在控制台上收到错误 “Uncaught SyntaxError: Unexpected token =>。但是,当我从括号中删除参数时没有错误。参数不应该有括号吗?

document.querySelector("#book-form").addEventListener("submit", (e) 
=> {
  // …
});

【问题讨论】:

  • 您是否粘贴到带有上述换行符的控制台?
  • 这可能被解释为(e); => {,因为分号注入,所以它不是有效的箭头函数。

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

箭头函数的参数和=>之间不能有换行符:

14.2 Arrow Function Definitions

ArrowFunction[In, Yield, Await]:

  • ArrowParameters [?Yield, ?Await] [这里没有 LineTerminator] => ConciseBody

要么删除换行符,要么将其放在其他位置。您也可以使用命名函数,例如:

const submitHandler = (e) => {
  // ...
};
document.querySelector("#book-form").addEventListener("submit", submitHandler);

【讨论】:

    【解决方案2】:

    首先,你的函数调用和函数声明没有关闭。其次,箭头不能单独在直线上。

    //Event: add book
    document.querySelector("#book-form").addEventListener("submit", (e) => {
      //prevent default
      e.preventDefault();
      // get form value
      const title = document.querySelector("#title").value;
      const author = document.querySelector("#author").value;
      const isbn = document.querySelector("#isbn").value;
    //Close function body, then function call.
    });
    

    【讨论】:

    • 哪些函数调用和函数调用声明没有关闭?
    • 见最后一行。对 addEventListener 的调用从未关闭,您的箭头函数体也没有关闭
    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2012-05-17
    • 2019-02-10
    • 2014-07-08
    • 2011-03-09
    • 2014-01-06
    • 2012-04-10
    相关资源
    最近更新 更多