索引值显示在终端上,但在尝试在代码中使用时未定义

the index value is shown on terminal but is undefined while trying to utilize in code

我正在尝试处理一些与日期密切相关的数据。如下面的代码片段所示,我试图找到离今天最近的一天的索引。我正在使用 date-fns 实用程序库来完成这项工作。当我尝试从中记录 closestIndex 时,它工作正常并在终端中得到输出,但当我尝试使用 closestIndex 的值时,我收到一条错误消息,显示 closestIndexundefined。 任何想法将不胜感激。

import * as dateFns from 'date-fns';

const today = new Date().getTime();
const dates = [
  2022-04-10T14:07:12.276Z,
  2022-04-10T14:07:06.967Z,
  2022-04-10T14:07:04.663Z,
  2022-04-10T14:07:03.040Z,
  2022-04-10T14:07:01.420Z,
  2022-04-10T14:06:59.869Z,
  2022-04-10T14:06:53.223Z
]

const closestIndex = dateFns.closestTo(today, dates);

console.log(closestIndex); // => 0

console.log(dates[closestIndex]); // => undefined could not be used as index value

您应该在数组中使用真正的 Date 对象(而不是甚至没有引用的 ISO-8601 值)并使用 closestIndexTo instead of closestTo(这将 return Date 值本身而不是它的 数组中的index)

const today = new Date().getTime();
const dates = [
  new Date('2022-04-10T14:07:12.276Z'),
  new Date('2022-04-10T14:07:06.967Z'),
  new Date('2022-04-10T14:07:04.663Z'),
  new Date('2022-04-10T14:07:03.040Z'),
  new Date('2022-04-10T14:07:01.420Z'),
  new Date('2022-04-10T14:06:59.869Z'),
  new Date('2022-04-10T14:06:53.223Z')
]

const closestIndex = dateFns.closestIndexTo(today, dates);

console.log(closestIndex); // => 0

console.log(dates[closestIndex]); // => "2022-04-10T14:07:12.276Z"
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>