首页 > 解决方案 > 如何使用回调函数使用地图方法javascript显示整个月份

问题描述

我是 javascript 的初学者。我想了解更多回调函数,因为我花了很多时间来学习这个函数,但我还没有清楚地理解。

这是我的代码。我想创建新函数(回调)以继续此代码,并使用方法图显示整个月

const getmonth = (callback) => {
    setTimeout(() => {
        let error = true;
        let month = ["January","February","March","April","Mey","Juny","July","August","September","October","November","Desember"];
        if(!error) {
            callback(null, month)
        } else {
            callback(new error("Data gak ketemu", []))
        }
    }, 4000)
}

标签: javascriptnode.js

解决方案


回调是函数,它作为参数传递给另一个函数。例如:

function sayHello(callback) {
  console.log('Hi everyone');
  setTimeout(function(){
    callback(); // execution your function with 3 seconds delay
  }, 3000);
}

在你的情况下(我没有使用箭头函数来让你更容易理解):

// Lets create a function, which will just print month which is passed as an argument
const printMonth = function(month) {
  console.log(month);
}

// Now we are using map function
// https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/map

month.map(function(month) {
  console.log(month); 
});

map函数接受另一个函数作为参数(称为回调),在此函数中,您可以对数组的每个元素做任何您想做的事情。您还可以使用 anreturn返回带有修改元素的新数组。


推荐阅读