提问人:ofg 提问时间:10/19/2023 更新时间:10/19/2023 访问量:49
为什么这个箭头函数看起来与我所学的不同?[复制]
Why does this arrow function look different from what I have learnt? [duplicate]
问:
我正在学习如何在 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);
} );
});
答: 暂无答案
评论
alert
addEventListener
why does 'function' not need to be declared here?
,我对这两个问题感到困惑。你从哪里得知箭头函数有(可以有)一个关键词?Why does this arrow function look different from what I have learnt?
function
buttons.forEach
button.addEventListener