为什么这个箭头函数看起来与我所学的不同?[复制]

Why does this arrow function look different from what I have learnt? [duplicate]

提问人:ofg 提问时间:10/19/2023 更新时间:10/19/2023 访问量:49

问:

我正在学习如何在 JS 中操作 DOM,并且对为什么传递给数组方法的箭头函数看起来如何感到困惑。在继续之前,我想先了解代码背后的逻辑。请查看代码中的 //。我已将该函数粘贴为普通函数和箭头函数,并将我的问题写在代码中。

const buttons = document.querySelectorAll('button');


buttons.forEach(function(button) { 
    button.addEventListener('click', function() {
        alert(button.id);
    });
});

buttons.forEach(button => { //why does 'function' not need to be declared here? 
    button.addEventListener('click', () => { // why does this need curly braces? Why can't the alert call stay on the same line? Also, I was taught that multiple line arrow functions must have 'return', but this clearly does not?
        alert(button.id);
    } );
    
});
JavaScript 箭头函数

评论

1赞 David 10/19/2023
在这个特定示例中,大括号是可选的,并且是样式偏好的问题。既不返回任何内容,也不返回任何内容,因此省略大括号不会改变任何内容。alertaddEventListener
0赞 t.niese 10/19/2023
why does 'function' not need to be declared here?,我对这两个问题感到困惑。你从哪里得知箭头函数有(可以有)一个关键词?Why does this arrow function look different from what I have learnt?function
1赞 jsejcksn 10/19/2023
^即使它们返回了值,这些值也未被 和 使用。buttons.forEachbutton.addEventListener
1赞 user229044 10/19/2023
您的问题都是基于误解或误解。如果您对箭头函数的语法有疑问,您可能应该去文档
0赞 ofg 10/19/2023
t.niese - 对不起,我理解这种困惑。我的意思不是给箭头函数一个函数关键字,而是在编写箭头函数时,通常会给它一个名字。然而,在这里,当它用作回调时,情况并非如此。为什么不呢?

答: 暂无答案