Why is the length not displayed as a key in an array object?

So, just a question about how an array works in a java script, here is some behavior;

var a = [1,2,3,4]
Object.keys(a)
>> ['0','1','2','3']
a['0']
>> 1
a.length
>> 4
a.something = 'value'
a
>> [1,2,3,4]
console.log(a)
>> [1, 2, 3, 4, something: "value"]
Object.keys(a)
>> ['0','1','2','3','something']
a.something
>> 'value'
a.length
>> 4
a.length = 5
a 
>>[1, 2, 3, 4, undefined]
console.log(a)
>>[1, 2, 3, 4, something: "value"]
Object.keys(a)
>> ["0", "1", "2", "3", "something"]
a.length = 'len'
> Uncaught RangeError: Invalid array length(…)

My question is: why is "length" not displayed as a key in an array object? It pretty much acts like it does, although it seems to have figured out an int. If it is not a function or key, what is it?

+4
source share
1 answer

length- a property of an object with a handle properties , enumerableset both false, therefore, it will not appear when you iterate through his keys

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

console.log(Object.getOwnPropertyDescriptor( a, 'length' ));

// => ... enumerable: false ...
Run codeHide result

I recommend this text , which is related to the question.

+6

Source: https://habr.com/ru/post/1622010/


All Articles