gpt4 book ai didi

javascript - 如何使用箭头函数编写这个回调代码?

转载 作者:行者123 更新时间:2023-11-28 16:56:58 24 4
gpt4 key购买 nike

这里是 JavaScript 和箭头函数的初学者。

我尝试将以下语法更改为箭头函数格式但失败。

正常功能:

function add(a, b, callback) {
document.write(`The sum of ${a} and ${b} is ${a + b}.` + `<br>`);
callback();
}

function secondLine(){
document.write("The callback must be printed after addition.");
}

add(1,2,secondLine)

箭头函数

((a, b, callback) => {
document.write(`The sum of ${a} and ${b} is ${a + b}.` + `<br>`);
callback();
})

(secondLine() => {
document.write("The callback must be printed after addition.");
})

(1,2,secondLine)

控制台只返回

The sum of function(){document.write("The callback must be printed after addition.");} and undefined is function(){document.write("The callback must be printed after addition.");}undefined.

我不应该在回调中使用箭头函数吗?如果我真的想使用回调,语法应该如何输入?

提前非常感谢。

最佳答案

您可以尝试以下方法:

(function(){
var add = (a, b, callback) => {
document.write(`The sum of ${a} and ${b} is ${a + b}.` + `<br>`);
callback();
}

var secondLine = () => {
document.write("The callback must be printed after addition.");
}
add(1,2,secondLine);
})();

关于javascript - 如何使用箭头函数编写这个回调代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com