亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用矩獲得數組中最近的下一次時間?

如何使用矩獲得數組中最近的下一次時間?

料青山看我應如是 2023-11-11 16:14:43
我想找到距離給定時間最近的下一個時間,我從堆棧溢出中得到了這段代碼,但我無法獲得所需的結果// Current time in millisconst now = +moment('10:07', 'HH:mm').format('x');// List of timesconst times = ["10:00", "10:18", "23:30", "12:00"];// Times in millisecondsconst timesInMillis = times.map(t => +moment(t, "HH:mm").format("x"));function closestTime(arr, time) {  return arr.reduce(function(prev, curr) {    return Math.abs(curr - time) < Math.abs(prev - time) ? curr : prev;  });}const closest = moment(closestTime(timesInMillis, now)).format('HH:mm');// closest is 10:00 but i want the next time 10:18console.log(closest);<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
查看完整描述

1 回答

?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

根本不需要片刻


24小時時間可排序,可直接比較


const times = ["10:00", "10:18", "23:30", "12:00"].sort();


const getClosest = targetTime => times.find(time => time >= targetTime) || "N/A";


console.log(getClosest("10:07"));


console.log(getClosest("11:30"));


console.log(getClosest("13:30"));


console.log(getClosest("23:40")); // not available in array


查看完整回答
反對 回復 2023-11-11
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號