Multiplication with date object - javascript

前端 未结 2 1488
陌清茗
陌清茗 2020-12-19 15:34

I came across this piece of code var timeStamp = 1 * new Date(); and to my surprise it returned value in milliseconds since 1970/01/01. This is equivalent to us

2条回答
  •  萌比男神i
    2020-12-19 15:57

    Numeric conversion

    It is because of numeric conversion in javascript which is almost same like toString but internally it is called much more often.

    Numeric conversion is performed in two main cases:

    • In functions which needs a number: for example Math.sin(obj), isNaN(obj), including arithmetic operators: +obj.
    • In comparisons, like obj == 'John'. The exceptions are the string equality ===, because it doesn’t do any type conversion, and also non-strict equality when both arguments are objects, not primitives: obj1 == obj2. It is true only if both arguments reference the same object.

    The explicit conversion can also be done with Number(obj).

    The algorithm of numeric conversion:

    • If valueOf method exists and returns a primitive, then return it.

    • Otherwise, if toString method exists and returns a primitive, then return it.

    • Otherwise, throw an exception.

    Among built-in objects, Date supports both numeric and string conversion:

    alert( new Date() ) // The date in human-readable form
    alert( 1*new Date() ) // Microseconds from 1 Jan 1970
    

    Further reading

提交回复
热议问题