Home > Article > Web Front-end > JavaScript sets or returns the length property of the number of elements in an array
Definition and Usage
The length property sets or returns the number of elements in an array.
Syntax
arrayObject.length
Description
The length property of an array is always 1 greater than the subscript of the last element defined in the array. For regular arrays with consecutive elements starting with element 0, the length property declares the number of elements in the array.
The length property of an array is initialized when the array is created using Constructor Array(). When a new element is added to the array, the value of length is updated if necessary.
Set the length property to change the size of the array. If set to a value smaller than its current value, the array will be truncated and its trailing elements will be lost. If the set value is greater than its current value, the array will grow and new elements will be added to the end of the array, with their value being undefined.
Example
In this example, we will show how to use the length property to return and set the length of an array:
<script type="text/javascript"> var arr = new Array(3) arr[0] = "John" arr[1] = "Andy" arr[2] = "Wendy" document.write("Original length: " + arr.length) document.write("<br />") arr.length=5 document.write("New length: " + arr.length) </script>
Output:
Original length: 3 New length: 5
About javascript Please see the following for a summary of the length attribute.
1. The length length property in
StringObject is the number of characters that returns the 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. 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
The above is the detailed content of JavaScript sets or returns the length property of the number of elements in an array. For more information, please follow other related articles on the PHP Chinese website!