Fun with Arrays: What Have I Done?

Discussion in 'Javascript' started by Gene Wirchenko, Nov 9, 2011.

  1. Dear JavaScripters:

    I do not remember where I got the idea that JavaScript can handle
    arrays with string indexes, but I decided to try it, because it could
    simplify certain code that I am planning.

    In the course of my experiments -- KRA-KOOM! -- I came up with
    the following code. I appear to have two slightly different arrays
    with some elements in common or one array with an alter ego. Could
    someone please explain why?

    ***** Start of Code *****
    <html>

    <!--
    try3.html
    Array Playaround
    Last Modification: 2011-11-08
    -->

    <head>
    <title>try3.html: Array Playaround</title>

    <script type="text/javascript">

    var Collection=new Array(3);
    Collection[0]="zero";
    Collection[1]="one";
    Collection[2]=2;
    Collection[3]="trois";
    Collection["seven"]=8-1;
    Collection[5]="cinq";

    for (var i=0; i<Collection.length; i++)
    alert(i+":"+Collection);

    for (i in Collection)
    alert(i+":"+Collection);

    </script>

    </head>

    <body>

    </body>

    </html>
    ***** End of Code *****

    The first loop outputs
    0:zero
    1:eek:ne
    2:2
    3:trois
    4:undefined
    5:cinq
    and the second loop outputs
    0:zero
    1:eek:ne
    2:2
    3:trois
    5:cinq
    seven:7

    What exactly did I do, please?

    Sincerely,

    Gene Wirchenko
     
    Gene Wirchenko, Nov 9, 2011
    #1
    1. Advertising

  2. Gene Wirchenko

    RobG Guest

    On Nov 9, 2:32 pm, Gene Wirchenko <> wrote:
    > Dear JavaScripters:
    >
    > I do not remember where I got the idea that JavaScript can handle
    > arrays with string indexes, but I decided to try it, because it could
    > simplify certain code that I am planning.


    In javascript, arrays are just objects with a special length property
    and some handy inherited methods. Otherwise, they are just like
    objects in that they are collections of name/value pairs, where the
    names are strings.


    > In the course of my experiments -- KRA-KOOM! -- I came up with
    > the following code. I appear to have two slightly different arrays
    > with some elements in common or one array with an alter ego. Could
    > someone please explain why?
    >
    > ***** Start of Code *****
    > <html>
    >
    > <!--
    > try3.html
    > Array Playaround
    > Last Modification: 2011-11-08
    > -->
    >
    > <head>
    > <title>try3.html: Array Playaround</title>
    >
    > <script type="text/javascript">
    >
    > var Collection=new Array(3);


    That creates an array with a length of 3. Variables starting with a
    capital letter are normally (by convention) reserved for constructors.
    Setting the length is usually unnecessary, the array can be
    initialised with:

    var collection = [];


    > Collection[0]="zero";


    Even though a number has been used to create the property, it is
    converted to a string to create a property named '0' and the value
    'zero' is assigned.

    > Collection[1]="one";
    > Collection[2]=2;
    > Collection[3]="trois";
    > Collection["seven"]=8-1;
    > Collection[5]="cinq";


    The length property is always one greater than the largest positive
    integer index, so the length is now 6. You could have initialised the
    array as:

    var collection = ['zero', 'one', 2, 'trois',,''cinq'];
    collection.seven = 8 - 1;

    Note that dot notation can be used for property access where the name
    follows the rules for valid identifiers, square bracket notation can
    be used for that and where the name isn't a valid identifier (e.g.
    it's a number).

    Also note the use of an elision between 'trois' and 'cinq'. It
    increases the length for that position but does not create a property
    '4' (well, at least not in browsers that conform to ECMA-262).

    >
    > for (var i=0; i<Collection.length; i++)
    > alert(i+":"+Collection);


    That uses an index to visit the properties named 0, 1, 2 etc. up to 5
    (converting numbers to strings for use as property names). Since there
    is no property for '4', collection[4] returns undefined. Also, it will
    not return any properties that aren't named 0 to 5 inclusive.

    >
    > for (i in Collection)
    > alert(i+":"+Collection);


    That will iterate over the enumerable properties of the array in an
    implementation dependent order. Since there is no property named '4',
    it will not be returned and since there is a property named 'seven',
    it will. For..in will also return enumerable properties on the
    prototype chain, so be careful of that.

    [...]
    > ***** End of Code *****
    >
    > The first loop outputs
    > 0:zero
    > 1:eek:ne
    > 2:2
    > 3:trois
    > 4:undefined
    > 5:cinq
    > and the second loop outputs
    > 0:zero
    > 1:eek:ne
    > 2:2
    > 3:trois
    > 5:cinq
    > seven:7
    >
    > What exactly did I do, please?


    Hopefully I've explained that above. Try it in various browsers and
    you'll see a difference in order returned by for..in (e.g. try it in
    IE 8, which returns the properties in the order they were added).

    --
    Rob
     
    RobG, Nov 9, 2011
    #2
    1. Advertising

  3. Gene Wirchenko

    RobG Guest

    On Nov 9, 3:30 pm, RobG <> wrote:
    [...]
    > The length property is always one greater than the largest positive
    > integer index


    That should be "... is always *at least* one greater ..." since the
    length can be set to any positive integer number (within the limits of
    0 to 2^32 - 1).

    Setting length higher than the highest index just increases the value
    of 'length', it doesn't create any extra properties. Setting it
    shorter truncates the array so the highest index is now one less than
    length and any elements with names equal to or greater than length are
    discarded.

    See ECMA-262 § 15.4.


    --
    Rob
     
    RobG, Nov 9, 2011
    #3
  4. Gene Wirchenko

    Tim Streater Guest

    In article <>,
    Gene Wirchenko <> wrote:

    > Dear JavaScripters:


    [snip]

    > What exactly did I do, please?


    What you did was not to get a book on JavaScript and read up about
    arrays and objects.

    --
    Tim

    "That excessive bail ought not to be required, nor excessive fines imposed,
    nor cruel and unusual punishments inflicted" -- Bill of Rights 1689
     
    Tim Streater, Nov 9, 2011
    #4
  5. On 11/09/2011 11:57 AM, Tim Streater wrote:
    > In article <>,
    > Gene Wirchenko <> wrote:
    >
    >> Dear JavaScripters:

    >
    > [snip]
    >
    >> What exactly did I do, please?

    >
    > What you did was not to get a book on JavaScript and read up about
    > arrays and objects.
    >


    That's what he didn't do, not what he did!

    Anyway, aren't people allowed to ask questions here any more?
     
    SteveYoungTbird, Nov 9, 2011
    #5
  6. Gene Wirchenko

    Elegie Guest

    On 09/11/2011 11:57, Tim Streater wrote :

    Hi Tim,

    >> What exactly did I do, please?

    >
    > What you did was not to get a book on JavaScript and read up about
    > arrays and objects.


    I don't really have a problem with that. The OP is a beginner, yet he
    did try out some things with arrays, before posting a clear case (which
    elicited an excellent answer by RobG).

    Imagine you try and learn Java. You start working with arrays, hear
    about lists, mix in generics, and a few test cases later you get strange
    issues. You post these, and the reply you get is "Don't bother us,
    invariance and covariance of entities are trivial stuff, RTFM". How do
    you feel?

    Don't get me wrong, reading books or specifications are definitely
    necessary steps to becoming a proficient programmer. However, I believe
    that the learning process is a progressive thing, and that you should
    not try to read all of them before interacting with other people. Not
    only you would not know if what you read is what should be read, you
    would not understand how the things you learn articulate together, and
    you would probably end building (slowly and painfully) a wrong
    representation of the technology (unless you're really bright).

    Just my 2c, YMMV.

    Kind regards,
    Elegie.
     
    Elegie, Nov 9, 2011
    #6
  7. Gene Wirchenko

    Tim Streater Guest

    In article <4eba62e3$0$681$>,
    Elegie <> wrote:

    > On 09/11/2011 11:57, Tim Streater wrote :


    > >> What exactly did I do, please?

    > >
    > > What you did was not to get a book on JavaScript and read up about
    > > arrays and objects.

    >
    > I don't really have a problem with that. The OP is a beginner, yet he
    > did try out some things with arrays, before posting a clear case (which
    > elicited an excellent answer by RobG).


    Oh indeed, and that's the best way to go: try things out and see what
    happens. All I'm saying is that the next step after that is to read your
    books and see if your observations make sense in the context of the
    book's content. A well-written book (as opposed to simply the language
    spec) will help the reader create a mental picture of what's going on.

    > Imagine you try and learn Java. You start working with arrays, hear
    > about lists, mix in generics, and a few test cases later you get strange
    > issues. You post these, and the reply you get is "Don't bother us,
    > invariance and covariance of entities are trivial stuff, RTFM". How do
    > you feel?


    Well annoyed obviously, if I *have* RTFM, and still have holes in my
    mental picture. Worst case in my personal experience was when I had an
    HTML table that was rendering funny. In alt.html all I got was the usual
    BS and people picking up on trivial matters (in the way that PointyHead
    does). Eventually someone with a bit more brains suggested adding a
    DOCTYPE to get my browser out of quirks mode, which solved my problem.

    In that instance, I'd probably read about quirks mode or DOCTYPEs in my
    books, but hadn't appreciated their significance. *That* is the point at
    which ng's come in to their own.

    So I don't think the OP shouldn't be asking questions, but it may be
    quicker to poke around the web first.

    --
    Tim

    "That excessive bail ought not to be required, nor excessive fines imposed,
    nor cruel and unusual punishments inflicted" -- Bill of Rights 1689
     
    Tim Streater, Nov 9, 2011
    #7
  8. On Wed, 09 Nov 2011 10:57:03 +0000, Tim Streater
    <> wrote:

    >In article <>,
    > Gene Wirchenko <> wrote:
    >
    >> Dear JavaScripters:

    >
    >[snip]
    >
    >> What exactly did I do, please?

    >
    >What you did was not to get a book on JavaScript and read up about
    >arrays and objects.


    I did. Unfortunately, the text does not cover some things. One
    tends to find out this when one tries looking something up. I did
    some Web searches to find out about string indexes for arrays. That
    did not completely cover it either though. I experimented and got
    some results which I wrote up.

    I would like to understand. That is why I asked.

    I am also very familiar with the phenomonen of missing something
    and having it pointed out casually by someone else. I would rather
    ask than slam myself into a wall.

    Sincerely,

    Gene Wirchenko
     
    Gene Wirchenko, Nov 9, 2011
    #8
  9. In comp.lang.javascript message <cbd20c37-234b-4bf5-acfc-658d3e5d4811@q3
    9g2000prg.googlegroups.com>, Tue, 8 Nov 2011 21:30:00, RobG
    <> posted:

    >On Nov 9, 2:32 pm, Gene Wirchenko <> wrote:


    >> I do not remember where I got the idea that JavaScript can handle
    >> arrays with string indexes, but I decided to try it, because it could
    >> simplify certain code that I am planning.


    As an experienced programmer (IIRC), you /should/ have got it from
    reading ECMA 262 version 5.1 section 15.4 paragraph 1, if not before.
    The standard is not suitable for novice programmers; but an experienced
    programmer, reading its words once through, should spot quite a few odd
    things in the language which it might be worth knowing the existence of.

    Unfortunately, there are many regions of the standard which are
    comparatively easy to understand.


    >The length property is always one greater than the largest positive

    the largest non-negative, I think.
    >integer index, so the length is now 6.

    and [].length = 0


    --
    (c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05.
    Website <http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
    PAS EXE etc. : <http://www.merlyn.demon.co.uk/programs/> - see in 00index.htm
    Dates - miscdate.htm estrdate.htm js-dates.htm pas-time.htm critdate.htm etc.
     
    Dr J R Stockton, Nov 10, 2011
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Andy Fish
    Replies:
    65
    Views:
    1,769
    Mabden
    May 18, 2004
  2. dolphin
    Replies:
    4
    Views:
    324
    Jorgen Grahn
    Aug 25, 2007
  3. Rick Dearman

    A bit of fun. A programming puzzle to be done in C.

    Rick Dearman, Jan 3, 2009, in forum: C Programming
    Replies:
    17
    Views:
    584
  4. er
    Replies:
    2
    Views:
    509
  5. Zhidian Du
    Replies:
    0
    Views:
    159
    Zhidian Du
    Feb 21, 2004
Loading...

Share This Page