我想将诸如getMinutes()
,getTime()
或getDay()
之类的日期对象方法作为回调传递给诸如以下的函数:
formatDate = (date, callback) => {
date.callback()
}
或更高级:
formatDateArray = (dateArray, callback) => {
dateArray.map(date => date.callback())
}
我有什么选择?
答案 0 :(得分:3)
您可以通过将日期对象作为Fuction.prototype.call
参数传递来使用Date
来调用this
方法:
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));
答案 1 :(得分:1)
尝试:
date[callback]()
var date=new Date();
var callbacks=["toLocaleString", "getFullYear", "valueOf"];
callbacks.forEach(cb=>console.log(cb+": "+date[cb]()));
答案 2 :(得分:1)
为此,我将使用咖喱函数:第一个调用采用您的回调(以及其他一些可选参数;稍后再介绍),第二个调用采用您的日期:
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"