JavaScript 过滤器助手中的精确字符串匹配未返回 true
exact string match is not returning true in JavaScript filter helper
我正在使用过滤器助手来创建一个新的与今天日期匹配的项目数组。我已经确认这两个比较都是长度为 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'
);
我正在使用过滤器助手来创建一个新的与今天日期匹配的项目数组。我已经确认这两个比较都是长度为 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'
);