转换毫秒的Javascript函数会产生奇怪的结果

转换毫秒的Javascript函数会产生奇怪的结果,javascript,Javascript,我正在为我正在制作的一个小型web应用程序创建自己的自定义TimeObject类 在这里,我定义了一个函数,以获取一个有效范围(整数毫秒数),以便实例化TimeObject,如下所示: TimeObject.prototype.millisecondsToTime = function(mm) { function valid() { if(parseInt(mm,10) >= 0 && parseInt(mm,10) <= 359999999)

我正在为我正在制作的一个小型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;
    }
}
诸如
1001
1003
,但不包括
1002
1004
的值分别返回
毫秒
0
2
。它们应该返回
1
3
作为
毫秒
值,但不返回

我知道这是一个逻辑错误,但这里发生了什么?我如何更正我的代码?

尝试先从计时器中减去较小的元素,逐步删除最小的单位,然后除以该单位中的值数

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;

这将避免在计算中出现任何非整数。

尝试使用整数代数,而不是多次除法和乘法。请记住,浮点运算会失去十进制精度不确定您是否误解了我的意图,但是使用您的代码可以处理
0
999
之间的
mm
的所有值,但只要我传入一个大于
999
的值,我就无法得到预期的结果。请参见此处(在浏览器中打开控制台):您可能希望
1000
毫秒设置为
0
秒设置为
1
,以及根据毫秒数适当传递的所有其他值。@nhuff717是的,对不起,我完全忘记了1000的一些因素。修改后的代码应该更容易理解,也许我的数学不够好,但是这个函数如何在几秒钟而不是几毫秒内改变?例如,如果我有1000秒,我是否仍然从移除最小单位(毫秒)开始?我正在为每种类型的单元(ms、s、m、h)编写一个函数。如果您的值是以秒为单位计算的(即Unix历元时间),只需删除前两行即可。
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;