When studying Section 7.1 of the Sixth Edition of "The Definitive Guide to JavaScript" to create an array through an array literal, we can not assign a value to an element of the array, otherwise it will be undefined. Although it is undefined, when we call the length property of the array object, undefined will also cause the length to be increased by 1. There are four situations as shown below:
var undef0 = [,,]; var undef1 = [1,,]; var undef2 = [,1,]; var undef3 = [,,1]; console.log(undef0.length); console.log(undef1.length); console.log(undef2.length); console.log(undef3.length);
We can guess the length of each of the four console.log outputs. Before, I would definitely guess that they were all 3. The actual result is as follows:
Why is this? The answer is: the syntax of array literals allows optional trailing commas, so [,,], [1,,], [,1,] In these three cases, the JS engine will think that the last comma is the ending comma, so it will think that there are only two elements. In the case of [,,1], an additional element is artificially added after the last comma, so the last comma It is not the end, so we can think that the length of [,,1,] is still 3.