回调函数中如何传递参数?

ADI*_*RAJ 0 javascript ecmascript-6

我已经开始学习用于 Web 开发的 JavaScript,目前我陷入了回调函数的某个点。问题是我无法理解 JavaScript 中参数是如何传递的。

代码:

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
function myfunc(value){ //i had set a parameter 'value'
  console.log(value); // i had printed the 'value'
}
arr.forEach(myfunc); // i had not passed any argument in myfunc
Run Code Online (Sandbox Code Playgroud)

我真的很困惑myfunc (value)如何从 forEach 函数或任何函数中获取“value”参数,例如:

const numbers1 = [45, 4, 9, 16, 25];
function myFunction(value) { //myFunction has parameter 'value'
  return value * 2;
}
const numbers2 = numbers1.map(myFunction); /* here, how value arguments are passed to 
myFunction? */
Run Code Online (Sandbox Code Playgroud)

Nic*_*wer 7

它们被传入是因为forEach有一些代码将它们传入。forEach 的实现将如下所示:

forEach(callback) {
  // `this` is the array we're looping over
  for (let i = 0; i < this.length; i++) {
    callback(this[i], i, this);
  }
}
Run Code Online (Sandbox Code Playgroud)

SoforEach处理循环数组的逻辑,然后对于数组中的每个元素,它将调用您的函数并传入三个参数(值、索引和整个数组)。您只需编写一个函数,以您需要的任何方式使用这些值。如果不需要使用全部 3 个参数,则只需省略所需参数右侧的任何参数即可。