2017-02-11 56 views

回答

4

這是預期的行爲,檢查MDN docs of Function.length

長度的函數對象的屬性,並表示該功能多少個參數預期,即正式參數的數量。此數字不包括其餘參數,僅包含第一個參數之前的參數,其默認值爲。相比之下,arguments.length對於一個函數是本地的,並且提供了實際傳遞給該函數的參數的數量。

+0

哦,太感謝你了!但是在這種情況下,我怎麼才能得到這個函數的長度呢? –

+0

@YingchXue:我不認爲有什麼辦法可以做到這一點..... –

2

MDN docs所述,

Function.length包括第一一用一 默認值之前參數。

在你的榜樣作用,第一個參數本身具有的1默認值,從而Function.length不包括你a以後提供的任何參數。

因此,它給你的價值0

爲了讓事情更清晰的考慮以下片段:

//no arguments with default value 
 
function f(a, b) { 
 
    console.log('hello'); 
 
} 
 
console.log('No of arguments ' + f.length);

輸出將是2

//second argument has defualt value. Thus only argument a that is before the 
 
//argument having default value is included by Function.length 
 
function f(a, b=1) { 
 
    console.log('hello'); 
 
} 
 
console.log(f.length);

輸出將是1

//second argument has defualt value . 
 
//but only arguments before the argument having default value are included 
 
//thus b and c are excluded 
 
function f(a, b=2, c) { 
 
    console.log('hello'); 
 
} 
 
console.log(f.length);

輸出爲1

+0

非常感謝你! –

+0

歡迎您:-) – varunsinghal65

相關問題