我制作了一个 Node.js 服务器,它每秒从 API 中提取数据,并在数据发生变化时存储它。站点的“数据”是一个对象,它也具有该数据的时间戳。如果我将此时间戳保存在数组中,如何找到最接近我输入的任何时间戳的时间戳? 不知道是否优化过,如果没有请提供更优化的解决方案或方法。
我也是 StackOverflow 的新手,我的英语可能很差,所以对错误感到抱歉。 我不知道它是否经过优化,但您可以创建一个名为“closest = null”的变量和另一个名为“difference = 0”的变量,然后循环遍历数组,从输入的时间戳中减去每个时间戳。对于每次迭代,检查减法的值是否大于或小于变量“distance”中的实际值,如果是,则将变量更改为该值以及与您减去的时间戳“最接近”的变量,否则继续循环。 比如:
//initializing example array
const list = [];
data1 = new Date();
data1.setFullYear(2024);
data1.setMonth(7);
data2 = new Date();
data2.setFullYear(2024);
data2.setMonth(8);
data3 = new Date();
data3.setFullYear(2024);
data3.setMonth(9);
list.push(data1, data2, data3);
//initialize variables to store the closest date and the difference between the entered date and the closest date
closest = null;
diff = 0;
//iterate over the array of dates
list.forEach((stamp) => {
//that will be the entered date you want, im using the current date
const data_hoje = new Date();
//if the closest date is null, set the current date as the closest date and calculate the difference between the current date and the closest date
if(closest == null) {
closest = stamp
diff = data_hoje - stamp
} else {
//if the difference between the current date and the closest date is less than the current difference, update the closest date and the difference
if(data_hoje - stamp < diff) {
closest = stamp
diff = data_hoje - stamp
}
}
})
//print the closest date - response is the timestamp of date3
console.log(closest);