提问者:小点点

如何使用回调函数用map method 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)
}

共2个答案

匿名用户

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

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函数接受另一个函数作为参数(称为回调),在这个函数中,您可以对数组的每个元素执行您想要的任何操作。 您还可以使用return返回带有修改过的元素的新数组。

匿名用户

回调通常用于在异步操作完成后继续代码执行。

有关回调函数的详细信息

您可以像这样在代码上创建回调函数。

getmonth((err,data)=>{
    if(!err){
        data.map(month =>month);
    }
    return err;
})