简体   繁体   中英

Why does this JavaScript function return: “0:0function toString() { [native code] }”?

I took the following function from this site and plugged it into my code to display a user-friendly time string based on a millisecond argument.

Why does this function not work?

    function getTimeFromMillis(millis)
    {

        milliSecs = millis;

        msSecs = (1000)
        msMins = (msSecs * 60)
        msHours = (msMins * 60)
        numHours = Math.floor(milliSecs/msHours)
        numMins = Math.floor((milliSecs - (numHours * msHours)) / msMins)
        numSecs = Math.floor((milliSecs - (numHours * msHours) - (numMins * msMins))/ msSecs)


        if (numSecs < 10){
          numSecs = "0" + numSecs.toString
        }
        if (numMins < 10){
          numMins = "0" + numMins.toString
        }

        resultString = numHours + ":" + numMins + ":" + numSecs     
        return resultString;

    }

If I pass it a millisecond value from my calling function I get this:

0:0function toString() { [native code] }:0function toString() { [native code] }

You forgot the () in your calls to "toString".

edit — sorry had to step away for a sec. As @Gareth commented, the references to "toString" are syntactically valid, as they're just references to functions. Thus the parser has no problems with your code. What goes wrong is when you implicitly convert those references to strings.

If you just add () to each call, it should work a lot better. Or, as that very page you linked to points out a few posts further down, you really don't need .toString() at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM