我不是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