前置加号如何处理新日期?

How does a prepending plus sign treat new Date?

我最近遇到了这行有趣的代码:

var date = +new Date;

console.log(date);

所以我尝试将 + 放在字符串之前,以便更好地理解发生了什么,这就是结果:

var one = +"1"; // -> 1
var negativeTwo = -"2"; // -> -2
var notReallyANumber = +"number: 1"; // -> NaN

console.log(one, negativeTwo, notReallyANumber);

似乎每当一个+符号或一个-符号放在一个字符串之前,它就将该字符串转换成一个数字,如果一个负号放在一个字符串之前,结果数将为负数。

最后,如果字符串不是数字,结果将是NaN

这是为什么?

如何在字符串前放置 +- 符号将其转换为数字?它如何也适用于 new Date

编辑:

How does a + sign affect new Date? How does the value Wed Nov 07 2018 21:50:30 GMT-0500 for example, convert into a numerical representation?

+ 将以下表达式转换为数字(如果可以)。如果下面的表达式是一个 object,那么这个对象的 valueOf 函数被调用,从而 returns the primitive value of the specified object 然后可以(试图)被强制到一个数字。

How does a + sign affect new Date? How does the value Wed Nov 07 2018 21:50:30 GMT-0500 for example, convert into a numerical representation?

Date.prototype.valueOf returns 相关日期对象的 整数 时间戳:

console.log(
  new Date().valueOf()
);

+Date 对象之前时确实会调用此方法,正如您在此处看到的(仅用于演示,这不应该在实际代码中):

Date.prototype.valueOf = () => 5;
console.log(+new Date());

因此,Date 对象通过 valueOf 转换为数字。 (这是 + 强制转换为数字的操作实际发生之前,但由于它已经是一个数字,因此不会进一步影响任何东西)