将功能转换为箭头功能

我正在尝试将功能转换为箭头功能,但无法正常工作。我在做一些错误吗,我的代码在下面。请引导我在哪里做错。

// Call Back Function 
 function ask(question, yes, no) { 
if (confirm(question)){
     yes()
 }
else {
    no()
}
}

function showOk() {
 console.log("you agreed")
}

function showCancel() {
console.log("canceled")
}

ask("do you agree ?", showOk, showCancel)


Arrow Function

let ask = (question, yes, no) => {if (confirm(question)) {
  yes()
} else {
  no()
}

let showOk = () => console.log("you agreed");

let showCancel = () => console.log("Canceled");
}
ask("do you agree ?", showOk, showCancel)
评论
ab_non
ab_non

For an arrow function to have an implicit return expression is required, so for each function, you have to return something, at least return true.

您的代码看起来像

let ask = (question, yes, no) => {
  if (confirm(question)) {
      return yes();
   }
   return no();
}

let showOk = () => {
  console.log("you agreed");
  return true;
};

let showCancel = () => {
    console.log("Canceled");
  return true;
};

ask("do you agree ?", showOk, showCancel);
点赞
评论
贪恋你温柔
贪恋你温柔

您有一个花括号来晚了。

一种较短的方法是将这些函数与条件语句一起使用。

const
    ask = (question, yes, no) => (confirm(question) ? yes : no)(),
    showOk = () => console.log("you agreed"),
    showCancel = () => console.log("Canceled");

ask("do you agree ?", showOk, showCancel);
点赞
评论