为什么一个大的正数小于0?

Why is a large positive number smaller than 0?

所以,我正在编写一个函数,通过比较分钟的差异来获取给定数组中今天最接近的日期。我有这个代码:

const getSelectedDate = () => {
    const today = moment(new Date()).format('YYYY-MM-DD');
    const dates = data.data;
    let minDiff = null;
    let closestDate = dates[0].startDate;
    dates.map((item) => {
        const diff = Math.abs(moment(today).diff(moment(item.startDate).format('YYYY-MM-DD'), 'minutes', true));
        console.log('Diff: ' + diff + ' for date: ' +  item.startDate + ' with minDiff: ' + minDiff);
        if(!minDiff || diff < minDiff) {
            minDiff = diff;
            closestDate = item.startDate;
        }
    });
    return closestDate;
}

问题是它 returns 从 16-04-2021 开始的最接近日期是 13-04-2021 而不是 16-04-2021 索引。

示例输出:

Diff: 5760 for date: 2021-04-12T16:00:00 with minDiff: null
Diff: 0 for date: 2021-04-16T16:00:00 with minDiff: 5760
Diff: 4320 for date: 2021-04-13T16:00:00 with minDiff: 0
Diff: 17280 for date: 2021-04-28T16:00:00 with minDiff: 4320
2021-04-13T16:00:00

比较时如何定义0?

if(!minDiff || diff < minDiff) {

所以如果 minDiff 是

   minDiff = diff;

然后用新的差值代替


您可能想要测试 minDiff === null 而不是测试它的非真实性。

问题在于您未设置 minDiff 的测试:

    if(!minDiff || diff < minDiff && minDiff !== 0) {...

如果 minDiff 的值为 0

,测试的第一部分 !minDiff 将 return true

您应该严格测试 null:

    if(minDiff === null || diff < minDiff) {...