问题:调用函数并传入一个匿名箭头函数,提醒拼接值

Question: Call the function and passing in an anonymous arrow function that alerts the spliced value

预先道歉,我对 JS 很陌生。对于这个问题,找不到我应该把箭头函数放在哪里的问题。我试过在调用函数时将它放在参数中,但这似乎是非常错误的。确切的问题是:再次调用processSplicedValue函数,但这次传入一个匿名箭头函数,警告拼接值。

const heroList = [
  "Batman",
  "SuperMan",
  "Ironman",
  "War Machine",
  "Black Widow",
  "SpiderMan",
];

function processSplicedValue(array, spliceInd, functionProcess) {
  var hero = heroList.splice(spliceInd, 1);
  functionProcess(hero);
}

processSplicedValue(processSplicedValueList, 0, () => alert);

我认为这应该有所帮助

processSplicedValue(processSplicedValueList, 0, message => alert(message));

在 Javascript 中,函数是第一个 class 公民,即它们可以像任何其他变量一样传递。

您将一个参数作为不带参数的函数传递,returns 另一个函数(此处为 alert)。因此,即使您在调用回调时传递一些参数 functionProcess(hero),它也不会执行任何操作。

但是您可以在回调中接受一个参数 (x),然后像这样在您的警报中使用它:

const heroList = [
  "Batman",
  "SuperMan",
  "Ironman",
  "War Machine",
  "Black Widow",
  "SpiderMan",
];

function processSplicedValue(array, spliceInd, functionProcess) {
  var hero = heroList.splice(spliceInd, 1);
  functionProcess(hero);
  console.log("[processSplicedValue] called")
}

processSplicedValue(heroList, 0, (x) => alert(x));

只需将 alert 作为回调传入即可,因为它只是另一个函数

const heroList = [
  "Batman",
  "SuperMan",
  "Ironman",
  "War Machine",
  "Black Widow",
  "SpiderMan",
];

function processSplicedValue(array, spliceInd, functionProcess) {
  var hero = heroList.splice(spliceInd, 1);
  functionProcess(hero);
  console.log("[processSplicedValue] called")
}

processSplicedValue(heroList, 0, alert);