Why stage.days array return a length of 0, but stage.days through it like an object? Its type is Array with a length of 0.

 var stage = { days: [] }; stage.days['11-2']= []; stage.days['11-3']= []; alert(stage.days.length); // 0 for(var it in stage.days){ debugger // stage.days['11-2'] } 

    1 answer 1

    The following two articles answer your question:

    Arrays with numeric indexes

    An array is a kind of object that is designed to store numbered values ​​and offers additional methods for conveniently manipulating such a collection.

    Working with Objects in JavaScript: Theory and Practice

    There are 6 basic ones in JavaScript - these are Undefined (meaning no value), Null, (boolean type), (string), Number (number) and Object (object).

    In this case, the first 5 are primitive data types, but Object is not. In addition, it can be conditionally assumed that the Object type has “subtypes”: an array (Array), a function (Function), a regular expression (RegExp) and others.
    This is a somewhat simplified description, but in practice it is usually sufficient.

    And a simple experiment:

     console.log(typeof []); // "object" 

    Additionally, read the article " Inheritance of classes in JavaScript ." There the case of inheritance Array from Object is just considered.


    It would be equally useful to read the article " Objects as associative arrays " (thanks to @AlexKrass for the tip).

    • one
      Probably it is worth adding about prototype inheritance, instead of "subtypes", which is also true, but not in the spirit of JS. - user207618
    • @Other, this is a quote from the article, not my words. In addition, this, in my opinion, will unduly complicate the answer. I added a link to an article on this topic with a parsed example of the inheritance of an array from an object. - VenZell
    • This is good, I am satisfied. And it will complicate ... this TS asked a good question, not about the bumphead, but about the internal kitchen of JS. So she wants to know more. So an extra link will be a plus. - user207618
    • one
      I think the topic about associative arrays and their imitation in JS through objects will also go well here - Alex Krass
    • @AlexKrass, thanks, supplemented the answer - VenZell