Reputation: 4479
So just a question about how the array works in java script, Here's 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 does 'length' not show up as a key in the array object? It pretty much acts like on, although It seems to get parsed to an int. If it's not a function or a key, what is it?
Upvotes: 4
Views: 120
Reputation: 30557
length
is an object propery with the property descriptor, enumerable
, set as false
. Thus, it will not show when you iterate over its keys
var a = [1,2,3,4];
console.log(Object.getOwnPropertyDescriptor( a, 'length' ));
// => ... enumerable: false ...
I recommend this text which is related to the question
Upvotes: 6