Home > Web Front-end > JS Tutorial > A brief analysis of the length attribute of function in JavaScript_Basic knowledge

A brief analysis of the length attribute of function in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 16:46:45
Original
1116 people have browsed it

[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, and 1 respectively. What do these numbers represent?

This is a question that many newcomers in the group have been asking. In fact, the length of the function gets the number of formal parameters.
Let’s take a quick look at an example:

Copy code The code is as follows:

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 through arguments inside the function without actually defining the parameters, length will only get 0.

Copy code The code is as follows:

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.

Copy code The code is as follows:

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template