2
头图

Preface

Hello everyone, I’m Lin Sanxin. Today I will tell function of length is calculated. I hope everyone can learn from it and consolidate the foundation.

Why

Why did I think of this knowledge point? Because last night, in a group, a classmate was discussing a byte-beating interview question

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

To be honest, I didn't answer this question at first. In fact, I know that the interviewer wants to test toString method on the Number prototype, but I am stuck on the problem of how much the length of That's why today's article

How much is it?

Number of formal parameters

Let's take a look at the following example

function fn1 () {}

function fn2 (name) {}

function fn3 (name, age) {}

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

It can be seen that function has as many formal parameters as length . But is this really the case? Continue to look down

Default parameters

If there are default parameters, what would be 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

Explained, function of length is the number of parameters before the first

Remaining parameters

In the formal parameters of the function, there is also the remaining parameter of . If there is a remaining parameter of , how will it be counted?

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

console.log(fn1.length) // 1

It can be seen that the remaining parameters are not length in the calculation of 061d502b2db6f0

Summarize

Before summarizing, let’s announce 123['toString'].length + 123 = ? the answer for 124

The summary is: length is an attribute value of the function object, which refers to the number of parameters that must be passed in the function, that is, the number of formal parameters. The number of formal parameters does not include the number of remaining parameters, only the number of parameters before the with a default value

Concluding remarks

I am Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends, fish together haha, fish school, add me, please note [think]

image.png


Sunshine_Lin
2.1k 声望7.1k 粉丝