首页 > 解决方案 > Using unary plus (+) to compare Dates for equality

问题描述

The most standard way in javascript way to compare dates that I've seen is

let a=new Date();
let b=new Date(a);

let equals = a.getTime()==b.getTime();    //true

/* a==b  is false */

but

let equals = +a == +b

works well, looks quite clear and saves typing. I haven't seen many examples of that way to compare dates, almost all use getTime().

Is there any drawback or problem with the unary + applied this way?

标签: javascriptdatecomparison

解决方案


客观上,不存在语用问题。一元+触发(通过抽象的 ToNumber 和 ToPrimitive 操作)上的操作,它返回相同valueOf的值。所以你得到相同的结果。DateDategetTime


推荐阅读