Home >Web Front-end >JS Tutorial >Summary of JavaScript Length property

Summary of JavaScript Length property

PHPz
PHPzOriginal
2016-05-16 15:34:241959browse

The javascript length attribute returns the number of characters in the string, and length can return the number of parameters of the function. Next, I will introduce the javascript length attribute to you through this article. Friends who are interested in the javascript length attribute can refer to this article

For a summary of the javascript length attribute, please see the following detailed explanation.

1. The length

length attribute in StringObject is the number of characters in the returned string.

For example:

// 普通字符串
var str = "abcdef";
console.log(str.length); // 6
// 数组
var str1 = new Array(1,2,3,4);
console.log(str1.length); // 4
// 数组与字符串
var str2 = str1 + str; // "abcdef1,2,3,4"
console.log(str2.length); // 13
// 对象和对象
var obj = {};
console.log(obj.length); // undefined
var obj += obj; // "[object Object][object Object]"
console.log(obj.length); // 30

2. The length in Function

length can return the number of parameters of the function.

var a = function(a,b,c,d){};
console.log(a.length); // 4
var b = RegExp;
console.log(b.length); //new RegExp(pattern, attributes)构造方法中有两个参数, 所以length为2

※ The length attribute of the arguments instance returns the actual number of parameters passed to the function by the calling program.

var a = function(){
  console.log(arguments.length); 
};
a(1,2,3); // 3
a(); // 0

Note: As we all know, there is no method overloading in JavaScript, and arguments instances can help us simulate method overloading.

The following is an example to introduce the javascript length attribute

definition and usage

length attribute can return a string number of characters.

Syntax

stringObject.length

Example

In this example, we will show how to use the length attribute to return the number of characters in a string:

<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)
</script>

Output:

12

The above is the summary of the JavaScript length attribute. I hope you like it. For more related tutorials, please visit JavaScript Video Tutorial!

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