Modify Array Length

Use “Array name.length” to get or modify the length of an array. The length of the array is calculated by adding 1 to the maximum index value of the element in the array. The example code is as follows.

var arr = [‘a’, ‘b’, ‘c’];

console.log(arr.length); // Output :3

In the code above, the last element in the array is c, which has an index of 2, so the length of the array is 3. Using arr.length, you can not only get the length of the array, but also modify the length of the array, as shown in the sample code below.

var arr1 = [1, 2];

arr1.length = 4; // It is larger than the original length

console.log(arr1); / / output: (4) [1, 2, the empty x 2]

var arr2 = [1, 2, 3, 4];

arr2.length = 2; // Less than the original length

console.log(arr2); // Output result: (2) [1, 2]

In the output of console.log(), the preceding “(4)” indicates the length of the array is 4, followed by the elements in the array, and emply indicates the empty elements. If the value of length is greater than the original number of elements in the array, the missing element will take up the position of the index game and become empty. If the value of length is less than the original number of elements in the array, the extra array elements will be discarded. When an empty element is accessed, the result is undefined. The sample code is as follows.

var arr = [1];

arr.length = 4; // Change the size of the array to 4

console.log(arr); // output: (4) [1, empty x 3]

console.log(arr[1]); // Output :www.cungun.com undefined

In addition to the above, there are three other common situations where empty elements occur.

// Case 1: An empty element appears when an array is created using a literal

Var arr = [1, 2, and 4);

console.log(arr); // Output result: (4) [1,2, empty, 4]

// new Array(); // new Array()

var arr = new Array(4);

console.log(arr); // Empty: (4) [empty x 4]

// Add a discontiguous element to the array

var arr= [1];

arr[3] = 4; // Adds an element to the array with index 3

console.log(arr); // empty: (1) [1, empty x 2, 4]