理解forEach方法参数的“必要性”

3

文档似乎暗示在forEach方法中,回调函数是必需的参数并且当前值(currentValue)是回调函数的必需参数:

enter image description here

不过,这段没有回调函数参数的代码也可以正常工作:

a = [1, 2, 3, 4, 5];

a.forEach(function () {
    console.log(5);
})

当MDN在某些参数周围排列'optional'时,我该如何理解它们不在其他参数周围?


1
可能是因为使用forEach而从未访问currentValue会毫无意义。 - charlietfl
1
回调函数中的参数都不是必需的。毕竟是提供了回调函数,所以.forEach无法因为它需要或不需要的参数数量而失败。如果您使用比声明更多的参数调用函数,则不会发生任何事情。 - VLAZ
2个回答

4

无法强制要求一个 function 接受必填参数。不过,如果不使用 currentValue 参数,则使用 forEach 没有任何意义;您并不一定需要使用其他参数。所有参数仍然传递给 function,如果打印出 arguments,就可以看到。

a = [1, 2, 3, 4, 5];
a.forEach(function () {
    console.log("Number of arguments:", arguments.length);
    console.log("Current value:", arguments[0]);
    console.log("Index:", arguments[1]);
    console.log("Original array:", arguments[2]);
})


感谢 @hev1。嗯,很烦人,不知道他们为什么在所有参数周围加上“可选”这个词,因为它们都是可选的。 - tonitone110
@tonitone110,很可能是因为在没有currentValue参数的情况下使用forEach没有意义。 - Unmitigated

1
在这种情况下,您不使用数组的任何元素,只打印5。对于主任务中的任何数组交互,您需要当前值以对数组进行某些操作。

a = [1, 2, 3, 4, 5];

a.forEach(function (currentValue) {
    console.log(currentValue, 5);
})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接