Home  >  Article  >  Web Front-end  >  Introduction to the use of the length attribute of JavaScript function_javascript tips

Introduction to the use of the length attribute of JavaScript function_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:36:171199browse

[1,2,3]. length can get 3, "123". length can also get 3, everyone who knows a little about js knows this.

But what will eval.length, RegExp.length, "".toString.length, 1..toString.length get?

We get 1, 2, 0, 1 respectively. What do these numbers represent?

In fact, the length of the function gets the number of formal 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 it very simple, but there are also special things. If the parameters are called via arguments inside the function without actually defining the parameters, length will only get 0.

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

This function can indeed pass in parameters, and the parameters are also called internally, but length cannot know the number of parameters passed in.
The number of actual parameters can only be obtained through arguments. length when the function is executed.

function test() { console.log( arguments.length );}
test(1,2,3); // 输出 3
test(1,2,3,4); // 输出 4

So the length attribute of a function can only get the number of its formal parameters, but not the number of actual parameters.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn