首页 > javascript > 我的代码运行良好的箭头函数和使用{},但删除{}时,我得到语法错误

我的代码运行良好的箭头函数和使用{},但删除{}时,我得到语法错误 (My code runs well with arrow function and using { }, but when { } are removed i'm getting syntax)

问题

我一直在学习JavaScript。当我浏览箭头函数时,我了解到使用箭头函数时不需要{}。请帮我理解。

这个工作:

document.querySelector('.myForm').addEventListener('submit', (event) => {
    event.preventDefault();
    console.log(event.target.username.value);
    console.log(event.target.realname.value);
});

但如果删除{},则会显示语法错误。我以前使用过的函数在没有{}的情况下工作得很好。

解决方法

{}仅在有多个语句时使用。例如,如果只有一个语句,则不需要使用{}

问题

I have been learning JavaScript. As I was going through arrow functions, I learned that the { } are not necessary when using arrow functions. Please help me understand.

This one works:

document.querySelector('.myForm').addEventListener('submit', (event) => {
    event.preventDefault();
    console.log(event.target.username.value);
    console.log(event.target.realname.value);
});

But if the { } are removed, it shows syntax error. The previous functions I worked with worked perfectly without the { }.

解决方法

The {} are used only when there are more than one statement. If there is only one statement , for example , there is no need of using { }

相似信息