Consider following snippet:
 var a = new Array(); a['key'] = 'value'; alert(a.length);
What value will be displayed in alert box?
Explanation
The expression a['key'] will add a property key to the array object.
To add an element to array:
a[0] = 'value';
console.log(a) // ['value']
Integer-key-ed elements are only elements of an array.

length property only counts properties that are integers.
Theory
  • Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.
    Read more: Indexed collections: Arrays and typed Arrays

Thanks, @monsieurtoul08 ! Updated explanation and added theory fact and link to more detailed information

2019 Mar 15, 3:35:59 PM

`length` property only counts properties that are integers

2019 Mar 15, 10:11:29 AM

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты