javascript - 如何使用回调函数使用地图方法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)
}
解决方案
回调是函数,它作为参数传递给另一个函数。例如:
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
返回带有修改元素的新数组。
推荐阅读
- java - 如果参数化查询是从受信任的应用程序系统中检索的输入,如何解决扫描的 sql 注入问题?
- python - Airflow + python 日志模块不写入日志文件
- javascript - 使用 postgresSQL 设置护照本地策略
- c++ - Eclipse C++ 中的漂亮打印适用于某些项目,但不适用于其他项目
- android - DND 开启时无法检测到振动模式
- c# - 无法激活请求的服务,WCF
- javascript - Discord.js:检测来自 Webhook 的消息
- java - Playframework JavaWS 记录正确的 curl 脚本,但无法正常工作
- javascript - React Router 是否会导致我的组件渲染两次?
- javascript - 简单分隔符之间匹配,但分隔符本身不匹配