Unary Plus: Converting Date Objects to Millisecond Timestamps
In JavaScript, you might encounter code that resembles:
function fn() {
return new Date;
}
This expression returns a timestamp representing the current time, rather than a full Date object. However, it's not immediately apparent what the plus sign ( ) does.
The answer lies in the unary plus operator. When applied to a value, it performs a to-number conversion. In this case:
let numMilliseconds = new Date;
is equivalent to:
let numMilliseconds = Number(new Date);
The Number function converts the Date object into a number, representing the number of milliseconds since the start of the Unix epoch (midnight UTC on January 1, 1970).
This technique is commonly used when you only need a timestamp, saving memory and eliminating the need to manually extract it from the Date object. Consult the MDN documentation and "XKCD: Unary Plus" for further insights.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3