Order of Key-Value pair ("associative arrays")

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Abdullah Kauchali

    Order of Key-Value pair ("associative arrays")

    Hi folks,

    Can one rely on the order of keys inserted into an associative Javascript
    array? For example:


    var o = new Object();

    o["first"] = "Adam";
    o["second"] = "Eve";
    o["third"] = "Cane";
    o["fourth"] = "Abel";

    ..
    ..
    ..

    //then

    for (var i in o){
    alert(i);
    }

    Is the order in this "for loop" *guaranteed* to be:
    first, second, third, fourth?

    Also, if the "third" key is deleted, is the order still guaranteed?

    I've tested this in IE and Firefox, and it seems to work. I'd be grateful
    for any links that indicate this in Javascript standards/specs.

    Many thanks & kind regards,

    Abdullah


  • ZER0

    #2
    Re: Order of Key-Value pair ("associat ive arrays")

    On Tue, 25 May 2004 12:35:50 +0200, Abdullah Kauchali wrote:

    [cut][color=blue]
    > Is the order in this "for loop" *guaranteed* to be:
    > first, second, third, fourth?[/color]

    Unfortunately, not.
    Depend of the browser's implementation of this aspect of ECMAScript
    specifications.

    In IE,old Netscape versions, and Gecko based browsers, the order is
    "chronological" .. But.. try with Opera.
    [color=blue]
    > for any links that indicate this in Javascript standards/specs.[/color]



    [for-in statement]
    "The mechanics of enumerating the properties (..) is
    implementation dependent. The order of enumeration is defined by the
    object. (..) "

    --
    ZER0://coder.gfxer.web-designer/

    ~ Come devo regolare la stampante laser per stordire?
    (How do I set a laser printer to stun?)

    on air ~ "Linkin Park - Somewhere I Belong (real song)"

    Comment

    • Abdullah Kauchali

      #3
      Re: Order of Key-Value pair ("associat ive arrays")


      "ZER0" <zer0.shock@lib ero.it> wrote in message[color=blue]
      > http://www.ecma-international.org/pu...T/Ecma-262.pdf
      >
      > [for-in statement]
      > "The mechanics of enumerating the properties (..) is
      > implementation dependent. The order of enumeration is defined by the
      > object. (..) "[/color]


      Ho bummer! :(

      Thanks for that Zero.

      Now, how do I accomplish the following if the order is not guaranteed:

      1. Put objects within the "collection ";
      2. Access each one according to the order in which they were put into the
      collection.

      So far, I have this:

      It seems to me that the most straight-forward answer would be to create
      another "collection " with index numbers beginning with 0 and then always
      incrementing for additions to the collections. Once a index/offset number
      is used, it cannot be reused.

      So, after some additions and deletions, I'll get something like:

      1, 2, 3, 7, 9, 11, 23

      if I wanted to add to this collection, the next one would be 24 and so on.

      Is that the most elegant solution?

      Kind regards

      Abdullah



      Comment

      • Douglas Crockford

        #4
        Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

        > Can one rely on the order of keys inserted into an associative Javascript[color=blue]
        > array? For example:
        >
        > var o = new Object();
        >
        > o["first"] = "Adam";
        > o["second"] = "Eve";
        > o["third"] = "Cane";
        > o["fourth"] = "Abel";[/color]

        No. The ECMAScript specification allows the contents of an object to be
        unordered. Most implementations do order the contents, but you should
        not rely on that.

        Also, the preferred way of initializing an object is with the object
        literal notation.

        var o = {first: "Adam", second: "Eve", third: "Cain",
        fourth: "Abel"};

        See http://www.JSON.org

        Comment

        • Abdullah Kauchali

          #5
          Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)


          "ZER0" <zer0.shock@lib ero.it> wrote in message[color=blue]
          > "chronological" .. But.. try with Opera.[/color]

          Just tried it with Opera 7.50 and it seems to honour the order in which it
          was originally put in - the same as IE and Mozilla/FF.

          Almost there, but no official sanction from the specs! :(


          Comment

          • ZER0

            #6
            Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

            On Tue, 25 May 2004 15:43:45 +0200, Abdullah Kauchali wrote:
            [color=blue]
            > Just tried it with Opera 7.50 and it seems to honour the order in which it
            > was originally put in - the same as IE and Mozilla/FF.[/color]

            The last Opera I've seen was 7.0; and in that version the order was
            different.

            So, Now Opera seems use the same order of IE and Gecko.. Good news.
            [color=blue]
            > Almost there, but no official sanction from the specs! :([/color]

            Yes, as I said is implementation dependent.

            --
            ZER0://coder.gfxer.web-designer/

            ~ Tutti quelli che credono nella psicocinesi, per favore alzino la mia
            mano.

            on air ~ "Avril Lavigne - Don't Tell Me"

            Comment

            • Abdullah Kauchali

              #7
              Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)


              "Douglas Crockford" wrote in message
              [color=blue]
              >var o = {first: "Adam", second: "Eve", third: "Cain",
              > fourth: "Abel"};[/color]


              I don't think I can do that. The key/value pairs are unknown until runtime.

              Unless, of course, I am unaware of the way to initialise the way you mention
              for key/value pairs only known at runtime, then I'd be glad to learn how to
              do it.

              Kind regards

              Abdullah


              Comment

              • Grant Wagner

                #8
                Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

                Abdullah Kauchali wrote:
                [color=blue]
                > "ZER0" <zer0.shock@lib ero.it> wrote in message[color=green]
                > > http://www.ecma-international.org/pu...T/Ecma-262.pdf
                > >
                > > [for-in statement]
                > > "The mechanics of enumerating the properties (..) is
                > > implementation dependent. The order of enumeration is defined by the
                > > object. (..) "[/color]
                >
                > Ho bummer! :(
                >
                > Thanks for that Zero.
                >
                > Now, how do I accomplish the following if the order is not guaranteed:
                >
                > 1. Put objects within the "collection ";
                > 2. Access each one according to the order in which they were put into the
                > collection.
                >
                > So far, I have this:
                >
                > It seems to me that the most straight-forward answer would be to create
                > another "collection " with index numbers beginning with 0 and then always
                > incrementing for additions to the collections. Once a index/offset number
                > is used, it cannot be reused.
                >
                > So, after some additions and deletions, I'll get something like:
                >
                > 1, 2, 3, 7, 9, 11, 23
                >
                > if I wanted to add to this collection, the next one would be 24 and so on.
                >
                > Is that the most elegant solution?
                >
                > Kind regards
                >
                > Abdullah[/color]

                That's pretty much what you do. You can wrap it in functions to make it easier
                to manage:

                function addToCollection (collection, collectionOrder , property, value) {
                collection[property] = value;
                collectionOrder .push(property) ;
                }

                function removeFromColle ction(collectio n, collectionOrder , property) {
                collection[property] = null;
                for (var i = 0; i < collectionOrder .length; i++) {
                if (collectionOrde r[i] == property) {
                collectionOrder[i] = null;
                break;
                }
                }
                }

                function dumpCollection( collection, collectionOrder ) {
                var output = [];
                for (var i = 0; i < collectionOrder .length; i++) {
                if (collectionOrde r[i] != null) {
                output.push(col lection[collectionOrder[i]]);
                }
                }
                return output;
                }

                var o = new Object();
                var oOrder = new Array();

                addToCollection (o, oOrder, "first", "Adam");
                addToCollection (o, oOrder, "second", "Eve");
                addToCollection (o, oOrder, "third", "Cane");
                addToCollection (o, oOrder, "fourth", "Abel");
                removeFromColle ction(o, oOrder, "second");
                addToCollection (o, oOrder, "fifth", "Noah");
                alert(dumpColle ction(o, oOrder));

                If you want to get really fancy, you could write a "Collection " object that
                encapsulates all this functionality:

                function Collection() {
                var collection = {};
                var order = [];

                this.add = function(proper ty, value) {
                if (!this.exists(p roperty)) {
                collection[property] = value;
                order.push(prop erty);
                }
                }
                this.remove = function(proper ty) {
                collection[property] = null;
                for (var i = 0; i < order.length; i++) {
                if (order[i] == property) {
                order[i] = null;
                break;
                }
                }
                }
                this.toString = function() {
                var output = [];
                for (var i = 0; i < order.length; i++) {
                if (order[i] != null) {
                output.push(col lection[order[i]]);
                }
                }
                return output;
                }
                this.getKeys = function() {
                var keys = [];
                for (var i = 0; i < order.length; i++) {
                if (order[i] != null) {
                keys.push(order[i]);
                }
                }
                return keys;
                }
                this.update = function(proper ty, value) {
                if (value != null) {
                collection[property] = value;
                }
                for (var i = 0; i < order.length; i++) {
                if (order[i] == property) {
                order[i] = null;
                order.push(prop erty);
                break;
                }
                }
                }
                this.exists = function(proper ty) {
                return collection[property] != null;
                }
                }

                var myCollection = new Collection();
                myCollection.ad d("first", "Adam");
                myCollection.ad d("second", "Eve");
                myCollection.ad d("third", "Cane");
                myCollection.ad d("fourth", "Abel");
                myCollection.re move("second");
                myCollection.ad d("fifth", "Noah");
                alert(myCollect ion.toString()) ;
                alert(myCollect ion.getKeys());
                myCollection.up date("first");
                alert(myCollect ion.toString()) ;
                alert(myCollect ion.exists("thi rd"));
                alert(myCollect ion.exists("som ething"));

                The one thing you can't do with my code is actually store a null value in a
                collection entry. If you need to be able to do that, then you should use
                another object inside Collection to track if a collection entry actually
                contains a value or not.

                --
                | Grant Wagner <gwagner@agrico reunited.com>

                * Client-side Javascript and Netscape 4 DOM Reference available at:
                *


                * Internet Explorer DOM Reference available at:
                *
                Learn with interactive lessons and technical documentation, earn professional development hours and certifications, and connect with the community.


                * Netscape 6/7 DOM Reference available at:
                * http://www.mozilla.org/docs/dom/domref/
                * Tips for upgrading JavaScript for Netscape 7 / Mozilla
                * http://www.mozilla.org/docs/web-deve...upgrade_2.html


                Comment

                • Abdullah Kauchali

                  #9
                  Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)


                  "Grant Wagner" <gwagner@agrico reunited.com> wrote in message

                  <humbling code example snipped>

                  OMG. Thank you so much. Beats the hell out of making the attempts on my
                  own!

                  Many thanks, once again,

                  Kind regards

                  Abdullah


                  Comment

                  • ZER0

                    #10
                    Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

                    On Tue, 25 May 2004 17:38:49 GMT, Grant Wagner wrote:
                    [color=blue]
                    >
                    > That's pretty much what you do. You can wrap it in functions to make it easier
                    > to manage:[/color]
                    [cut][color=blue]
                    > If you want to get really fancy, you could write a "Collection " object that
                    > encapsulates all this functionality:[/color]

                    An Additional note: This code on IE, works only for version 5.5 or major;
                    because it use the push() array's method.

                    --
                    ZER0://coder.gfxer.web-designer/

                    ~ You don't have to be crazy to be a webmaster. But it helps.

                    Comment

                    • Grant Wagner

                      #11
                      Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

                      ZER0 wrote:
                      [color=blue]
                      > On Tue, 25 May 2004 17:38:49 GMT, Grant Wagner wrote:
                      >[color=green]
                      > > That's pretty much what you do. You can wrap it in functions to make it easier
                      > > to manage:[/color]
                      > [cut][color=green]
                      > > If you want to get really fancy, you could write a "Collection " object that
                      > > encapsulates all this functionality:[/color]
                      >
                      > An Additional note: This code on IE, works only for version 5.5 or major;
                      > because it use the push() array's method.
                      >
                      > --
                      > ZER0://coder.gfxer.web-designer/
                      >
                      > ~ You don't have to be crazy to be a webmaster. But it helps.[/color]

                      if (typeof Array.prototype .push != 'function') {
                      Array.prototype .push = function() {
                      for (var i = 0 ; i < arguments.lengt h ; i++) {
                      this[this.length] = arguments[i];
                      }
                      }
                      }

                      --
                      | Grant Wagner <gwagner@agrico reunited.com>

                      * Client-side Javascript and Netscape 4 DOM Reference available at:
                      *


                      * Internet Explorer DOM Reference available at:
                      *
                      Learn with interactive lessons and technical documentation, earn professional development hours and certifications, and connect with the community.

                      * Netscape 6/7 DOM Reference available at:
                      * http://www.mozilla.org/docs/dom/domref/
                      * Tips for upgrading JavaScript for Netscape 7 / Mozilla
                      * http://www.mozilla.org/docs/web-deve...upgrade_2.html


                      Comment

                      • ZER0

                        #12
                        Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

                        On Wed, 26 May 2004 13:21:55 GMT, Grant Wagner wrote:
                        [color=blue][color=green]
                        >> An Additional note: This code on IE, works only for version 5.5 or major;
                        >> because it use the push() array's method.[/color][/color]
                        [color=blue]
                        > if (typeof Array.prototype .push != 'function') {[/color]
                        [cut]

                        Better. :)

                        --
                        ZER0://coder.gfxer.web-designer/

                        ~ Plagiarism is copying from one source;
                        research is copying from two or more
                        (Wilson Mizner)

                        Comment

                        • Thomas 'PointedEars' Lahn

                          #13
                          Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

                          Abdullah Kauchali wrote:
                          [color=blue]
                          > Can one rely on the order of keys inserted into an associative Javascript
                          > array? For example:[/color]

                          JavaScript and other ECMAScript implementations have no built-in
                          concept of associative arrays.
                          [color=blue]
                          > var o = new Object();
                          >
                          > o["first"] = "Adam";
                          > o["second"] = "Eve";
                          > o["third"] = "Cane";
                          > o["fourth"] = "Abel";[/color]

                          That is an Object object on which alphabetic properties are added, not
                          an array. Try o.length or o.push(), neither is present or works, while
                          o.first, o.second aso. work. (If properties are identifiers, they can
                          be accessed both with the square bracket and the dot accessor.)

                          Using Mozilla/5.0 and a for-in-loop, properties are iterated in the
                          order of assignment, but there is no standard that specifies that.

                          Additional note: Even

                          var a = new Array();
                          a[0] = 42;
                          a["foo"] = "bar";

                          creates an array with *one* element, not two:

                          alert(a.length) ; // 1

                          var s = "";
                          for (var i in a)
                          {
                          s += i + " == " + a[i] + "\n";
                          }
                          alert(s);


                          PointedEars

                          Comment

                          • John G Harris

                            #14
                            Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

                            In article <40B94760.10403 01@PointedEars. de>, Thomas 'PointedEars' Lahn
                            <PointedEars@nu rfuerspam.de> writes[color=blue]
                            >Abdullah Kauchali wrote:
                            >[color=green]
                            >> Can one rely on the order of keys inserted into an associative Javascript
                            >> array? For example:[/color]
                            >
                            >JavaScript and other ECMAScript implementations have no built-in
                            >concept of associative arrays.[/color]
                            <snip>

                            It's the other way round. Every ECMAScript object is an associative
                            array.

                            Even Array objects are associative arrays. It's a syntax fudge that
                            makes Array objects look, almost, like the arrays in other languages
                            with their numeric indexes.

                            John
                            --
                            John Harris

                            Comment

                            • Lasse Reichstein Nielsen

                              #15
                              Re: Order of Key-Value pair (&quot;associat ive arrays&quot;)

                              John G Harris <john@nospam.de mon.co.uk> writes:
                              [color=blue]
                              > It's the other way round. Every ECMAScript object is an associative
                              > array.[/color]

                              .... where "associativ e array" is just mumbo-jumbo for a mapping from
                              something to something. I believe the name comes from Perl, although
                              they could have taken it from somewhere else. It is really a misnomer,
                              as it has nothing to do with "real" arrays.

                              In, e.g., Java, I would never say "associativ e array". I'd just say
                              "Map".

                              /L
                              --
                              Lasse Reichstein Nielsen - lrn@hotpop.com
                              DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                              'Faith without judgement merely degrades the spirit divine.'

                              Comment

                              Working...