我想将Date对象的方法,例如getMinutes()
、getTime()
或getDay()
作为回调函数传递给以下函数:
formatDate = (date, callback) => {
date.callback()
}
更高级的技术:
formatDateArray = (dateArray, callback) => {
dateArray.map(date => date.callback())
}
我的可选方案有哪些?
我想将Date对象的方法,例如getMinutes()
、getTime()
或getDay()
作为回调函数传递给以下函数:
formatDate = (date, callback) => {
date.callback()
}
formatDateArray = (dateArray, callback) => {
dateArray.map(date => date.callback())
}
我的可选方案有哪些?
Function.prototype.call
,将日期对象作为this
参数传递来调用Date
方法:
const getTime = Date.prototype.getTime;
const getDay = Date.prototype.getDay;
const getMinutes = Date.prototype.getMinutes
formatDateArray = (dateArray, callback) => {
return dateArray.map(date => callback.call(date))
}
console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getTime));
console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getDay));
console.log(formatDateArray([new Date(), new Date('August 17, 2020 03:24:00')], getMinutes));
const formatDate = (fn, ...args) => date => fn.apply(date, args);
Date#getDate
一起:const getDate = formatDate(Date.prototype.getDate);
getDate
现在是一个“等待”它的最后一个参数(即日期)的函数,所以您也可以将其与Array#map
一起使用:// moon landing dates
const apollo11 = new Date('1969-07-20');
const apollo12 = new Date('1969-11-21');
getDate(apollo11);
//=> 20
[apollo11, apollo12].map(getDate);
//=> [20, 21];
Date#toLocaleDateString
。如果不能使用它们将是一件遗憾的事情。由于它们是在实际日期之前提供的,因此我们可以创建专门的函数:const toUsDate = formatDate(Date.prototype.toLocaleDateString, 'en-US');
const toGbDate = formatDate(Date.prototype.toLocaleDateString, 'en-GB');
toUsDate(apollo11); //=> "7/20/1969"
toGbDate(apollo11); //=> "20/07/1969"
尝试:
date[callback]()
var date=new Date();
var callbacks=["toLocaleString", "getFullYear", "valueOf"];
callbacks.forEach(cb=>console.log(cb+": "+date[cb]()));
callback
的值:date[callback]()
。用法类似于formatDate(date, "getMinutes")
。 - Nick Parsons