简体   繁体   中英

Why does length not appear as a key in an array object?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM