回调函数
什么是回调函数:简单来说我在定义函数的时候有些条件是不能写死的,但是又不知道如何去写,所以我希望在定义函数的时候你给我传入一个函数,当执行这个函数的时候再去执行传进来的函数。参数中传入的函数我们称之为回调函数(callback)。
const data = [1, 2, 3, 4];
function test(arr, fn) {
for (let i = 0; i < arr.length; i++) {
console.log(fn(i));
}
}
function test2(index) {
return index;
}
test(data, test2);
因为函数在执行中需要一些参数所以可以将test函数中一些数据例如(i)传过去。