Home > Web Front-end > JS Tutorial > The impact of omitting elements on array length in JavaScript

The impact of omitting elements on array length in JavaScript

高洛峰
Release: 2016-12-08 16:22:16
Original
1263 people have browsed it

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);
Copy after login

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:

The impact of omitting elements on array length in JavaScript

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.

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