我不是100%确定为什么您能够使用Math.max()函数计算多个Date对象的最大日期。我的IDE PhpStorm
不断给我下面的错误:使用Math.max()计算最大JavaScript日期对象文档
Argument type Date is not assignable to parameter type number
在我的代码片段说明它是分配给参数:
/* Variable Defaults */
var dateOne = new Date();
var dateTwo = new Date('2017-01-21');
var dateThree = new Date('11/16/2016');
var dateMax = Math.max(dateOne, dateTwo, dateThree);
/* Console Data */
console.log('dateOne', dateOne);
console.log('dateTwo', dateTwo);
console.log('dateThree', dateThree);
console.log('dateMax', dateMax + ': ' + new Date(dateMax));
我决定寻找到了规范来查看我的IDE是否使用了较老的标准,但是我的研究未能实现我对自己为什么要使用这种方法的愿望:
ECMAScript 1st Edition (ECMA-262)
15.8.2.11 max(x, y)
- Returns the larger of the two arguments.
- If either argument is NaN, the result is NaN.
- If x>y, the result is x.
- If y>x, the result is y.
- If x is +0 and y is +0, the result is +0.
- If x is +0 and y is -0, the result is +0.
- If x is -0 and y is +0, the result is +0.
- If x is -0 and y is -0, the result is -0.
15.8.2.11 max ([ value1 [ , value2 [ , … ] ] ])
- Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.
- If no arguments are given, the result is −∞.
- If any value is NaN, the result is NaN.
- The comparison of values to determine the largest value is done as in 11.8.5 except that +0 is considered to be larger than −0.
- The length property of the max method is 2.
ECMAScript 2015 (6th Edition, ECMA-262)
20.2.2.24 Math.max (value1, value2 , …values)
- Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.
- If no arguments are given, the result is −∞.
- If any value is NaN, the result is NaN.
- The comparison of values to determine the largest value is done using the Abstract Relational Comparison algorithm (7.2.11) except that +0 is considered to be larger than −0.
- The length property of the max method is 2.
ECMAScript Latest Draft (ECMA-262)
20.2.2.24 Math.max (value1, value2, ...values)
- Given zero or more arguments, calls ToNumber on each of the arguments and returns the largest of the resulting values.
- If no arguments are given, the result is -∞.
- If any value is NaN, the result is NaN.
- The comparison of values to determine the largest value is done using the Abstract Relational Comparison algorithm except that +0 is considered to be larger than -0.
我已经在所有现代浏览器中测试过这种方法,并没有产生任何错误。虽然我不知道这是否与旧版浏览器兼容。
为什么Math.max()
的工作是通过传递Date
对象时的规范明确指出它不应该这样做?
因为强制类型转换,数学.max,需要数字。所以它会将日期转换为数字。所以PHPStorm是错误的,它看起来像Intellisense,正在说胡话。 – Keith
我不知道你为什么认为“* ...规范明确表明它不应该?”当他们没有人说。除了第一个,说“* ...对每个参数调用ToNumber ... *”(这是没有这么说的编辑1)。要了解[* ToNumber *](http://ecma-international.org/ecma-262/8.0/#sec-tonumber)如何处理日期,请点击链接。简而言之,它会调用* valueOf *,它会返回内部的[*时间值*](http://ecma-international.org/ecma-262/8.0/#sec-time-values-and-time-range ),这是一个数字(和*可能是'NaN',BTW)。 – RobG
@RobG谢谢你的解释。我现在看到了。当我问这个问题时,我的印象是'Date'对象是'NaN'。显然,我错了。 – Daerik