我正在使用过滤器助手来创建与今天的日期匹配的新项目数组。我已经确认这两个比较都是长度为 10 的字符串,但在过滤器中进行比较时,它们没有被识别为匹配项。
我知道它与新的 Date() 方法有关,因为当我针对日期字符串测试它时,第一次比较有效,而新的 Date 方法则不然。
if(chosenDate === 'today') {
// this does not work even though both values are equal
const scheduled = this.props.scheduled.filter(event => event.scheduled_at.substring(0, 10) === new Date(), 'yyyy-MM-dd');
// this works
const scheduled = this.props.scheduled.filter(event => event.scheduled_at.substring(0, 10) === '2019-11-14');
// this does not work
const scheduled = this.props.scheduled.filter(event => '2019-11-14' === new Date(), 'yyyy-MM-dd');
console.log(scheduled)
}
console.log(this.props.scheduled[0].scheduled_at.substring(0, 10));
console.log(dateFnsFormat(new Date(), 'yyyy-MM-dd'));
为什么新的日期字符串比较不相等?
最佳答案
看来你的意思是
const scheduled = this.props.scheduled.filter(event =>
event.scheduled_at.substring(0, 10) === dateFnsFormat(new Date(), 'yyyy-MM-dd')
);
但是写了
const scheduled = this.props.scheduled.filter(event =>
event.scheduled_at.substring(0, 10) === new Date()
, 'yyyy-MM-dd'
);
关于javascript - JavaScript 过滤器助手中的精确字符串匹配未返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58868180/