這聽起來像一個簡單的問題,但我沒有運氣搜索。 +d
injavascript:加變量前的符號
function addMonths(d, n, keepTime) {
if (+d) {
是什麼意思?
這聽起來像一個簡單的問題,但我沒有運氣搜索。 +d
injavascript:加變量前的符號
function addMonths(d, n, keepTime) {
if (+d) {
是什麼意思?
文檔:https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2b_(Unary_Plus%29 –
)對,Paul。@amateur,詳情如下:https:// developer .mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2b_(Unary_Plus) –
任何人蔘加混淆JavaScript比賽? –
它是產生數字表達式的一元「+」運算符。我相信這與d*1
相同。
正如其他答案中所解釋的那樣,它將變量轉換爲數字。當d可以是一個數字或函數時,該函數的計算結果爲一個數字時特別有用。
實施例(使用問題的addMonths
功能):
addMonths(function(){return x*y;}, 1, true);
addMonths(34,1,true);
addMonths("34",1,true);
則+d
將評估爲在所有情況下的數字。因此,根據d
是否是可以轉換爲數字的數字,函數或字符串,避免需要檢查類型並採用不同的代碼路徑。
'+ d'不會以addMonths –
的第一個調用示例爲真,我不知道我在寫這些時做了什麼。 '+ function(){...}'會產生一個'NaN'而不是評估函數 – ecerulm
可能重複[加號在'return + new Date'中做什麼](http://stackoverflow.com/questions/221539/what-does-the-plus-sign-do-in-return-新的日期) – nawfal
同樣的問題,但其他頁面的標題並沒有描述一般情況下,因爲這樣做 – geotheory
可能重複[JavaScript中的'+ ...'的含義](https://stackoverflow.com/q/15129137/1048572) – Bergi