[英]Convert function to arrow function
我正在嘗試將 function 轉換為箭頭 function 但它不起作用。 我做錯了我的代碼如下。 請指導我在哪里做錯了。
// 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)
你有一個大括號遲到了。
一種更短的方法是使用帶有條件語句的函數。
const ask = (question, yes, no) => (confirm(question)? yes: no)(), showOk = () => console.log("you agreed"), showCancel = () => console.log("Canceled"); ask("do you agree?", showOk, showCancel);
它可能會拋出 ReferenceError,因為 showOk 和 showCancel 是在箭頭 function 的 scope 中聲明的,而不是全局聲明的。
對於箭頭 function 需要有一個隱式返回表達式,所以對於每個 function,你必須返回一些東西,如果你使用 {},至少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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.