A brief analysis of the length attribute of function in javascript

  • 2020-03-30 03:06:55
  • OfStack

[1, 2, 3]. Length  We can get 3, "123". You can also get a 3, which anyone who knows a little bit about js knows.

But   Eval. Length, RegExp. Length, "".tostring.length, 1.. The toString. Length  What do you get?

I get 1,2,0,1. What do these Numbers represent?

This is a question many new friends in the group have been asking, in fact, the length of the function is the number of parameters.
Let's take a quick look at an example:

function test(a,b,c) {}
test.length // 3
function test(a,b,c,d) {}
test.length // 4

Isn't that simple, but it's also special that if the argument is called internally through arguments without actually defining the argument, the length will only get 0.

function test() { console.log( arguments );}
test.length // 0

This function does pass in arguments, and it calls arguments internally, but length does not know the number of arguments passed in.
Passed only while the function is executing; The arguments. Length  I get the number of arguments.

function test() { console.log( arguments.length );}
test(1,2,3); //The output of 3
test(1,2,3,4); //The output of 4

So the length property of a function gets only the number of arguments, not the number of arguments.

Related articles: