2017-02-11 59 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

相关问题