Line break within arrow function throws “Uncaught SyntaxError: Unexpected token `=>`”

折月煮酒 提交于 2020-07-31 05:18:37

问题


I’m getting the error “Uncaught SyntaxError: Unexpected token => on my console when I put the e parameter in parentheses and then use an ES6 arrow function. However, there’s no error when I remove the parameter from the parentheses. Should the parameter not have parentheses?

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

回答1:


Arrow functions cannot have a newline between the parameters and the =>:

14.2 Arrow Function Definitions

ArrowFunction[In, Yield, Await]:

  • ArrowParameters [?Yield, ?Await] [no LineTerminator here] => ConciseBody

Either remove the newline, or put it somewhere else. You could also use a named function instead, eg:

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



回答2:


First of all, your function call and function declarations are not closed. Secondly, the arrow cannot be on its line alone.

//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.
});


来源:https://stackoverflow.com/questions/57867784/line-break-within-arrow-function-throws-uncaught-syntaxerror-unexpected-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!