4

95%的人都回答不上来的问题:函数的length是多少?

 2 years ago
source link: https://segmentfault.com/a/1190000041201277
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

大家好,我是林三心,我今天给大家讲讲functionlength,到底是怎么算的。希望大家能从中学到东西,并且可以巩固一下基础。

为什么我会想到这个知识点呢?因为昨晚,在一个群里,有一位同学在讨论一道字节跳动的面试题

123['toString'].length + 123 = ?

说实话这道题,我一开始也没答出来。其实我是知道,面试官想考Number原型上的toString方法,但是我卡在了toString函数的length是多少这个难题上。所以才有了今天这篇文章

到底是多少?

咱们来看看下面这个例子

function fn1 () {}

function fn2 (name) {}

function fn3 (name, age) {}

console.log(fn1.length) // 0
console.log(fn2.length) // 1
console.log(fn3.length) // 2

可以看出,function有多少个形参,length就是多少。但是事实真是这样吗?继续往下看

如果有默认参数的话,函数的length会是多少呢?

function fn1 (name) {}

function fn2 (name = '林三心') {}

function fn3 (name, age = 22) {}

function fn4 (name, age = 22, gender) {}

function fn5(name = '林三心', age, gender) { }

console.log(fn1.length) // 1
console.log(fn2.length) // 0
console.log(fn3.length) // 1
console.log(fn4.length) // 1
console.log(fn5.length) // 0

说明了,functionlength,就是第一个具有默认值之前的参数个数

在函数的形参中,还有剩余参数这个东西,那如果具有剩余参数,会是怎么算呢?

function fn1(name, ...args) {}

console.log(fn1.length) // 1

可以看出,剩余参数是不算进length的计算之中的

总结之前,先公布123['toString'].length + 123 = ?的答案是124

总结就是:length 是函数对象的一个属性值,指该函数有多少个必须要传入的参数,即形参的个数。形参的数量不包括剩余参数个数,仅包括第一个具有默认值之前的参数个数

我是林三心,一个热心的前端菜鸟程序员。如果你上进,喜欢前端,想学习前端,那咱们可以交朋友,一起摸鱼哈哈,摸鱼群,加我请备注【思否】

image.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK