What does the plus sign do in '+new Date'

2018-12-31 20:17发布

问题:

I\'ve seen this in a few places

function fn() {
    return +new Date;
}

And I can see that it is returning a timestamp rather than a date object, but I can\'t find any documentation on what the plus sign is doing.

Can anyone explain?

回答1:

that\'s the + unary operator, it\'s equivalent to:

function(){ return Number(new Date); }

see: http://xkr.us/articles/javascript/unary-add/

and in MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus



回答2:

JavaScript is loosely typed, so it performs type coercion/conversion in certain circumstances:

http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html
http://www.jibbering.com/faq/faq_notes/type_convert.html

Other examples:

>>> +new Date()
1224589625406
>>> +\"3\"
3
>>> +true
1
>>> 3 == \"3\"
true


回答3:

Here is the specification regarding the \"unary add\" operator. Hope it helps...



回答4:

A JavaScript date can be written as a string:

Thu Sep 10 2015 12:02:54 GMT+0530 (IST)

or as a number:

1441866774938

Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00.

Coming to your question it seams that by adding \'+\' after assignment operator \'=\' , converting Date to equal number value.

same can be achieve using Number() function, like Number(new Date());

var date = +new Date(); //same as \'var date =number(new Date());\'


回答5:

It is a unary add operator and also used for explicit Number conversion, so when you call +new Date(), it tries to get the numeric value of that object using valueOf() like we get string from toString()

new Date().valueOf() == (+new Date)  // true


回答6:

Just to give some more info:

If you remember, When you want to find the time difference between two Date\'s, you simply do as following;

var d1 = new Date(\"2000/01/01 00:00:00\"); 
var d2 = new Date(\"2000/01/01 00:00:01\");  //one second later

var t = d2 - d1; //will be 1000 (msec) = 1 sec

typeof t; // \"number\"

now if you check type of d1-0, it is also a number:

t = new Date() - 0; //numeric value of Date: number of msec\'s since 1 Jan 1970.
typeof t; // \"number\"

that + will also convert the Date to Number:

typeof (+new Date()) //\"number\"

But note that 0 + new Date() will not be treated similarly! it will be concatenated as string:

0 + new Date() // \"0Tue Oct 16 05:03:24 PDT 2018\"


回答7:

It does exactly the same thing as:

function(){ return 0+new Date; }

that has the same result as:

function(){ return new Date().getTime(); }