[英]Javascript function to convert milliseconds yields strange results
我正在為正在制作的小型Web應用程序創建自己的自定義TimeObject
類。
在這里,我定義一個函數以采用有效范圍的整數毫秒數,以實例化TimeObject
,如下所示:
TimeObject.prototype.millisecondsToTime = function(mm) {
function valid() {
if(parseInt(mm,10) >= 0 && parseInt(mm,10) <= 359999999) return true;
}
if(valid()) {
var h = Math.floor(mm/3600000);
var m = Math.floor(((mm/3600000)-h)*60);
var s = Math.floor(((((mm/3600000)-h)*60)-m)*60);
var mmFinal = Math.floor(((((((mm/3600000)-h)*60)-m)*60)-s)*1000);
this.hours = h,
this.minutes = m;
this.seconds = s;
this.milliseconds = mmFinal;
} else {
this.hours = 0,
this.minutes = 0;
this.seconds = 0;
this.milliseconds = 0;
}
}
除了2 ^ x的值外,它似乎工作正常:
// 2^0 = 1 -> returns 0, should return 1
// 2^1 = 2 -> returns 1, should return 2
// 2^2 = 4 -> returns 3, should return 4
// 2^3 = 8 -> returns 7, should return 8
// And so on...
值,如1001
, 1003
,但不是1002
和1004
返回milliseconds
為0
和2
分別。 它們應返回1
和3
作為milliseconds
值,但不返回。
我知道這是一個邏輯錯誤,但是這里發生了什么以及如何糾正我的代碼?
嘗試先從計時器中減去較小的元素,然后逐步刪除最小的單位,然后除以該單位中的值數。
this.milliseconds = mm % 1000;
mm = (mm - this.milliseconds) / 1000; // mm is now measured in whole seconds
this.seconds = mm % 60;
mm = (mm - this.seconds) / 60; // mm is now measured in whole minutes
this.minutes = mm % 60;
mm = (mm - this.minutes) / 60; // mm is now measured in whole hours
this.hours = mm;
等等。這樣可以避免任何非整數數字出現在您的計算中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.