function f(a=1, b) {
console.log(a, b);
}
console.log(f.length);
的功能,我想獲得f的長度一樣f.length
,但我得到的是沒有。但是當我將a
更改爲沒有默認值的正常形式參數時,f.length
的結果爲,爲什麼?
function f(a=1, b) {
console.log(a, b);
}
console.log(f.length);
的功能,我想獲得f的長度一樣f.length
,但我得到的是沒有。但是當我將a
更改爲沒有默認值的正常形式參數時,f.length
的結果爲,爲什麼?
這是預期的行爲,檢查MDN docs of Function.length
:
長度的函數對象的屬性,並表示該功能多少個參數預期,即正式參數的數量。此數字不包括其餘參數,僅包含第一個參數之前的參數,其默認值爲。相比之下,arguments.length對於一個函數是本地的,並且提供了實際傳遞給該函數的參數的數量。
如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
非常感謝你! –
歡迎您:-) – varunsinghal65
哦,太感謝你了!但是在這種情況下,我怎麼才能得到這個函數的長度呢? –
@YingchXue:我不認爲有什麼辦法可以做到這一點..... –