Do array elements remove their own properties?

In JavaScript, when you define an array using literal syntax, the elements of the array can be omitted with additional commas:

a = [1, 2, 3]; // 1, 2, 3 b = [1, , 2, 3]; // 1, undefined, 2, 3 

I noticed that when accessing values ​​that the missing values ​​were not “native properties”

 b.hasOwnProperty(1); //false 

In contrast, if you define an array that explicitly sets undefined , it will be set as a "native property":

 c = [1, undefined, 2, 3]; c.hasOwnProperty(1); //true 

Is there a behavior to define elements of omitted elements defined in the specification? If so, which spec and where?

(additional bonus) Is it a reliable cross-browser, for example, confirmed by compatibility tables?

+5
source share
2 answers

Is the behavior of the parameter of omitted array elements defined in the specification?

Yes.

If so, what spec

ECMAScript specification. At least in versions 3, 5, 5.1 and 6.

and where?

In the semantics of literal array expressions specified by the array initializer section ( ES5 , ES6 ). It says:

[...] the missing element of the array contributes to the length of the array and increases the index of subsequent elements [, but they] are not defined.

When evaluating expressions, they are simply skipped - they are counted, but do not create a data property in the array instance, unlike assignment expressions that create elements.

Is it a reliable cross browser?

Yes, even old internet researchers do it. The only quirks are that they consider the final comma as elision , which it should not be, and getting .length wrong.

+3
source

Do some array elements ever create their own property?

From the squint comment that received the Annotated ECMAScript 5.1 document,

Elements with Eired elements are not defined .

Please note that this does not mean undefined . So no, the excluded element is undefined and therefore hasOwnProperty() returns false .

0
source

All Articles