文档似乎表明,在forEach方法中,回调函数是强制参数,而currentValue是回调函数的强制参数:

但是,该代码--没有回调函数的参数--运行良好:
a = [1, 2, 3, 4, 5];
a.forEach(function () {
console.log(5);
})
当MDN在某些参数周围“可选”而不是在其他参数周围时,我该如何理解?
发布于 2020-06-27 20:49:00
没有办法强制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]);
})
发布于 2020-06-27 20:49:51
在本例中,您不使用任何数组元素,只需打印5。对于主要任务--任何数组的交互--您需要currentValue对数组进行一些操作
a = [1, 2, 3, 4, 5];
a.forEach(function (currentValue) {
console.log(currentValue, 5);
})
https://stackoverflow.com/questions/62615390
复制相似问题