簡體   English   中英

為什么這個 function 不返回指定范圍的時間?

[英]Why is this function doesn't returns a time for the range specified?

考慮以下代碼,

 // Code from https://stackoverflow.com/a/66035934/14659574 const getRandomTime = (offsetHour = 0, rangeInHours = 2) => { const curTicks = Date.now() + 0 * (offsetHour*60*60*1000); const addTicks = (Math.random()*rangeInHours)*60*60*1000; return new Date(curTicks + addTicks); }; console.log((new Date())); for(let i=0; i<10;i++) { console.log( getRandomTime(1, 2+i)); }

它不尊重范圍,而是返回超出范圍的隨機時間。 我想要一個范圍內的隨機時間。

例如,假設我想要一個 2 小時后的隨機時間,但是這個 function 給了我從現在起 5 小時的值。

代碼取自我之前的問題 看起來答案的作者是不活躍的,所以我決定提出一個后續問題。

我有計算障礙,無法調試。 我什至嘗試了 label 的數字,但它沒有去任何地方。

這段代碼有什么問題?

我相信這個錯誤是在這部分: Date.now() + 0 * (offsetHour * 60 * 60 * 1000); .

通過將偏移小時乘以零,您實際上將其重置為零並否定偏移量。

因此,無法從 UTC 更改起點。

從方法中刪除0 *后,它按預期工作:

 const getRandomTime = (offsetHour = 0, rangeInHours = 2) => { // Removed the offending 0 * const curTicks = Date.now() + (offsetHour * 60 * 60 * 1000); const addTicks = (Math.random() * rangeInHours) * 60 * 60 * 1000; return new Date(curTicks + addTicks); }; // Prints a time between UTC-5 and 1 hour from then. console.log("Up to one hour from now: ",getRandomTime(-5, 1)); // Prints a time between UTC-5 and 2 hours from then. console.log("Up to two hours from now: ",getRandomTime(-5, 2)); // Example continues console.log("Up to three hours from now: ",getRandomTime(-5, 3)); console.log("Up to four hours from now: ",getRandomTime(-5, 4));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM