Object as key for associative array

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • JehanNYNJ@aol.com

    Object as key for associative array

    Is it possible to have an Object as the key for an Associative array
    like in the following example....


    function Obj(var1, var2)
    {
    this.var1 = var1;
    this.var1 = var1;


    }
    function test() {
    var sectionArray = new Array();
    var obj = new Obj("c","k");
    var obj2 = new Obj("3","n");
    var obj3 = new Obj("v","qk");

    sectionArray[obj] = "king";
    sectionArray[obj2] = "queen";
    sectionArray[obj3] = "joker";
    alert(sectionAr ray[obj]);
    }

    This does not give any error but the alert says "joker" instead of
    "king". Is there anything wrong with my code or is an Object something
    that just can not be used as a key.

    If it is the latter can someone please suggest another way for me to do
    it? Can I use a concatenated String instead of an object? My only
    problem then is how would I extract the values from the String, does
    JavaScript have a tokenizer method like Java?

    Thanks for any help.

  • Lee

    #2
    Re: Object as key for associative array

    JehanNYNJ@aol.c om said:[color=blue]
    >
    >Is it possible to have an Object as the key for an Associative array
    >like in the following example....
    >
    >
    >function Obj(var1, var2)
    >{
    > this.var1 = var1;
    > this.var1 = var1;
    >
    >
    >}
    >function test() {
    > var sectionArray = new Array();
    > var obj = new Obj("c","k");
    > var obj2 = new Obj("3","n");
    > var obj3 = new Obj("v","qk");
    >
    > sectionArray[obj] = "king";
    > sectionArray[obj2] = "queen";
    > sectionArray[obj3] = "joker";
    > alert(sectionAr ray[obj]);
    >}
    >
    >This does not give any error but the alert says "joker" instead of
    >"king". Is there anything wrong with my code or is an Object something
    >that just can not be used as a key.
    >
    >If it is the latter can someone please suggest another way for me to do
    >it? Can I use a concatenated String instead of an object? My only
    >problem then is how would I extract the values from the String, does
    >JavaScript have a tokenizer method like Java?[/color]

    The index has to be a string, so Javascript converts your Object to a string
    using the default toString() method, which returns "[Object]" (or something like
    that). Define your own toString() method that returns a unique value.

    And be aware that Javascript doesn't have true associative arrays. The
    attribute names of any Object can be used as if they were indices to return
    their values.

    Comment

    • humbads

      #3
      Re: Object as key for associative array

      If you're trying to put objects into an associative array without a
      unique key, then there is probably something wrong with your concept of
      the data structure. Maybe try something like this, which is an
      associative hash of objects, keyed by a string. (Note that JS1.2
      object literal/initializer syntax allows you to specify both the
      properties and values in-line. Also, note two ways to reference the
      object.)

      var cards = {
      "king": { num:13, let:"k" },
      "queen": { num:12, let:"q" },
      "jack": { num:11, let:"j" }
      };

      alert('queen is: '+cards["queen"].num+' '+cards.queen.l et);

      Comment

      • JehanNYNJ@aol.com

        #4
        Re: Object as key for associative array

        Can you show me how to define the toString () method ?

        Comment

        • humbads

          #5
          Re: Object as key for associative array

          function Obj(var1, var2) {
          this.var1 = var1;
          this.var2 = var2;
          }

          var obj = new Obj("c","k");
          var obj2 = new Obj("3","n");

          Obj.prototype.t oString = function() {
          return this.var1+' '+this.var2;
          }

          alert(obj.toStr ing());
          alert(obj2.toSt ring());

          (Tested)

          BTW, a great reference for Javascript can be found in an unlikely
          place, the Windows Scripting Reference .chm help file. The index is
          very handy.

          http://tinyurl.com/7rk6 - Download Windows Scripting Reference

          Comment

          • Thomas 'PointedEars' Lahn

            #6
            Re: Object as key for associative array

            humbads wrote:
            [color=blue]
            > function Obj(var1, var2) {
            > this.var1 = var1;
            > this.var2 = var2;
            > }
            >
            > var obj = new Obj("c","k");
            > var obj2 = new Obj("3","n");
            >
            > Obj.prototype.t oString = function() {
            > return this.var1+' '+this.var2;
            > }
            >
            > alert(obj.toStr ing());
            > alert(obj2.toSt ring());
            >
            > (Tested)[/color]

            The most interesting thing about the alert() method is that it automatically
            converts the argument to string *for display* [in all UAs that implement
            DOM Level 0 which actually defines alert()], using its toString() method if
            such is defined. So the special call of toString() here is unnecessary and
            thus reduces performance.


            PointedEars
            --
            Faulheit und Feigheit sind die beiden Ursachen, warum ein Teil der Menschen
            [...] gerne zeitlebens unmündig bleibt, und warum es anderen so leicht wird,
            sich zu deren Vormündern aufzuwerfen. Es ist so bequem, unmündig zu sein.
            -- Immanuel Kant

            Comment

            • Lasse Reichstein Nielsen

              #7
              Re: Object as key for associative array

              Thomas 'PointedEars' Lahn <PointedEars@we b.de> writes:
              [color=blue][color=green]
              >> alert(obj.toStr ing());[/color][/color]
              ....[color=blue]
              > The most interesting thing about the alert() method is that it automatically
              > converts the argument to string *for display* [in all UAs that implement
              > DOM Level 0 which actually defines alert()],[/color]

              (if "DOM Level 0" was itself defined in any way sufficient to give it
              a name ... i.e., alert is an entirely de-facto standard with no common,
              official definition)
              [color=blue]
              > using its toString() method if such is defined.[/color]

              Probably uses internal conversion, equivalent to doing:
              String(object)
              rather than:
              object.toString ()
              which also allows for "null" and "undefined" values. That will, in turn,
              call toString *if* the argument is an object.

              But that's just pedantism, for the actual arguments of this example,
              the statement is correct.
              [color=blue]
              > So the special call of toString() here is unnecessary and thus
              > reduces performance.[/color]

              Unnecessary, yes. Reduces performance ... no. It's hard to reduce the
              performance of something that blocks for user input :)

              /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

              • Thomas 'PointedEars' Lahn

                #8
                Re: Object as key for associative array

                Lasse Reichstein Nielsen wrote:
                [color=blue]
                > Thomas 'PointedEars' Lahn <PointedEars@we b.de> writes:[color=green][color=darkred]
                >>> alert(obj.toStr ing());
                >>> [...][/color]
                >> The most interesting thing about the alert() method is that it
                >> automatically converts the argument to string *for display* [in
                >> all UAs that implement DOM Level 0 which actually defines alert()],[/color]
                >
                > (if "DOM Level 0" was itself defined in any way sufficient to give it
                > a name ... i.e., alert is an entirely de-facto standard with no common,
                > official definition)[/color]

                ,-<http://www.w3.org/TR/DOM-Level-2-HTML/glossary.html>
                |
                | [...]
                | DOM Level 0
                | The term "DOM Level 0" refers to a mix (not formally specified) of
                | HTML document functionalities offered by Netscape Navigator version
                | 3.0 and Microsoft Internet Explorer version 3.0. In some cases,
                | attributes or methods have been included for reasons of backward
                | compatibility with "DOM Level 0".

                DOM Level 0, components of it defined in the Netscape JavaScript 1.3
                Reference, has been widely implemented in J(ava)Script-capable UAs
                since IE3/NN3:

                <http://web.archive.org/web/20040202050531/devedge.netscap e.com/library/manuals/2000/javascript/1.3/reference/>
                <http://web.archive.org/web/200402141...w.html#1201497
                [color=blue]
                > [...][color=green]
                >> So the special call of toString() here is unnecessary and thus
                >> reduces performance.[/color]
                >
                > Unnecessary, yes. Reduces performance ... no. It's hard to reduce the
                > performance of something that blocks for user input :)[/color]

                Well, the alert() window will disappear a little time later than without it.
                This *is* a degradation of performance, yet not a significant one for *one*
                call. Furthermore, do you know a reference that states alert() windows
                should not be displayed asynchronically ?


                PointedEars

                Comment

                • Thomas 'PointedEars' Lahn

                  #9
                  Re: Object as key for associative array

                  Thomas 'PointedEars' Lahn wrote:
                  [color=blue]
                  > Well, the alert() window will disappear a little time later than without
                  > it. [...][/color]

                  Err, s/dis//


                  PointedEars

                  Comment

                  • Lasse Reichstein Nielsen

                    #10
                    Re: Object as key for associative array

                    Thomas 'PointedEars' Lahn <PointedEars@we b.de> writes:
                    [color=blue]
                    > Lasse Reichstein Nielsen wrote:[/color]
                    [color=blue][color=green]
                    >> (if "DOM Level 0" was itself defined in any way sufficient to give it
                    >> a name ... i.e., alert is an entirely de-facto standard with no common,
                    >> official definition)[/color]
                    >
                    > ,-<http://www.w3.org/TR/DOM-Level-2-HTML/glossary.html>
                    > |
                    > | [...]
                    > | DOM Level 0[/color]

                    Ok, I'll have to admit that "DOM Level 0" is a name that *is* being
                    used by even the W3C, albeit to refer to a non-defined subset of
                    (non-standardized) functionality of earlier browsers.

                    The name is misleading, because it suggests that there is a definition
                    (as for DOM levels 1 and 2) and that it has something to do with
                    documents (the D in DOM).
                    [color=blue]
                    > DOM Level 0, components of it defined in the Netscape JavaScript 1.3
                    > Reference, has been widely implemented in J(ava)Script-capable UAs
                    > since IE3/NN3:[/color]

                    There are lots of features defined in these documents. Some are in the
                    set commonly considered DOM Level 0, others aren't (e.g., the java*
                    objects, layers, watch/unwatch methods on objects, etc.). If there
                    is a consensus about what DOM Level 0 contains at all, that is.
                    [color=blue][color=green]
                    >> Unnecessary, yes. Reduces performance ... no. It's hard to reduce the
                    >> performance of something that blocks for user input :)[/color]
                    >
                    > Well, the alert() window will disappear a little time later than without it.
                    > This *is* a degradation of performance, yet not a significant one for *one*
                    > call.[/color]
                    [correcte to "appear a little time later" in other post]

                    Not for any amount of calls. The millisecond extra time is dwarfed by
                    the time it takes for user interaction. More time is wasted if the
                    user blinks while reading the message.
                    [color=blue]
                    > Furthermore, do you know a reference that states alert() windows
                    > should not be displayed asynchronically ?[/color]

                    That would bring me back to the "no common official definition" :)

                    DOM Level 0, as the term is used by the W3C, refers to Netscape
                    Navigator 3 (JavaScript v1.1) and IE 3 (JScript v2).

                    You pointed out the definition of alert() in JavaScript v1.1, which
                    doesn't say anything about being synchroneous or asynchroneous. It
                    might be implicit in calling it a "dialog window".

                    The JScript definition is:
                    URL:http://msdn.microsoft. com/workshop/author/dhtml/reference/methods/alert.asp>
                    It says even less (but does say: "There is no public standard that applies to this method.")


                    The most current definition would be the Gecko DOM reference, which is
                    also the only one to classify methods as "DOM Level 0. Not part of
                    specification". It says less than the JavaScript 1.1 reference.
                    <URL:http://www.mozilla.org/docs/dom/domref/dom_window_ref2 .html#1016766>

                    So, no, alert() could be asynchroneous without braking anything but
                    tradition. But I guess that's what DOM Level 0 is: A name for "how
                    it traditionally is".

                    /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

                    • humbads

                      #11
                      Re: Object as key for associative array

                      > But I guess that's what DOM Level 0 is: A name for "how
                      it traditionally is".

                      My Oreilly Javascript book (4th edition) says, "... the Document
                      objects that have become de facto standards ... are known as the Level
                      0 DOM, because they form a base level of document functionality that
                      Javascript programmers can rely on in all browsers."

                      Therefore, no standards setting organization (SSO) has defined Level 0
                      DOM, but since you can expect those objects in all browsers, it is a de
                      facto standard. I think that a de facto standard is just as
                      well-defined as an SSO-ratified standard, for all practical purposes.
                      And I think the name is appropriate too, even if slightly misleading.

                      Just my two cents.

                      Comment

                      • Richard Cornford

                        #12
                        Re: Object as key for associative array

                        humbads wrote:[color=blue][color=green]
                        >> But I guess that's what DOM Level 0 is: A name for "how
                        >> it traditionally is".[/color]
                        >
                        > My Oreilly Javascript book (4th edition) says, "... the
                        > Document objects that have become de facto standards ...
                        > are known as the Level 0 DOM, because they form a base
                        > level of document functionality that Javascript programmers
                        > can rely on in all browsers."
                        >
                        > Therefore, no standards setting organization (SSO) has
                        > defined Level 0 DOM, but since you can expect those
                        > objects in all browsers, it is a de facto standard.
                        > I think that a de facto standard is just aswell-defined
                        > as an SSO-ratified standard, for all practical purposes.
                        > And I think the name is appropriate too, even if slightly
                        > misleading.[/color]
                        <snip>

                        The problem with asserting that an unwritten DOM level 0 is a de facto
                        standard is that you don't know what exactly it is that is in that
                        standard. If you define it as 'the features you can expect to find in
                        all browsers, and are not explicitly defined an any real standards',
                        then you can 'rely on those features in all browsers'. But you then need
                        to be familiar with the DOMs of *all* browsers in order to know what is
                        in that 'level 0 standard' and what is not (Which is not a realistic
                        requirement).

                        Take the global - Option - constructor, for example. Many would
                        categorise it as DOM level zero but you will not find it on NetFront 4.

                        Richard.


                        Comment

                        Working...