Adding elements with concatination to an Array

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

    Adding elements with concatination to an Array

    I am trying to add an element to an array like this:

    var ty = [99, 100];
    zz = "ty";
    var ab = null;

    zz+="[23]";

    ab = eval(zz);
    document.write( ab.length);

    But it don't work. What am I doing wrong??


  • Michael Winter

    #2
    Re: Adding elements with concatination to an Array

    On 29/05/2005 21:53, JS wrote:
    [color=blue]
    > I am trying to add an element to an array like this:
    >
    > var ty = [99, 100];
    > zz = "ty";
    > var ab = null;
    >
    > zz+="[23]";
    >
    > ab = eval(zz);[/color]

    [snip]

    Simplifying that code, you get:

    var ty = [99, 100],
    ab = eval('ty[23]');

    which can be simplifier further to:

    var ty = [99, 100],
    ab = ty[23];

    Basically, you create an array with two elements that contain the
    numbers 99 and 100, then attempt to assign the 23th element (which is
    undefined) to the variable, ab.

    To append a value to an array, you can use the push method:

    ty.push(23);

    This accepts any number of arguments and adds them all in left-to-right
    order. You can also concatenate two arrays together with the concat method:

    ty.concat([23]);

    Mike


    Note that the push method isn't implements by JScript versions prior to
    5.5 (and therefore, usually IE versions prior to 5.5) so it may require
    emulation:

    if('function' != typeof Array.prototype .push) {
    Array.prototype .push = function() {
    var i = 0, j = this.length, n = arguments.lengt h;

    while(i < n) {this[j++] = arguments[i++];}
    return j;
    };
    }

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail.

    Comment

    • JS

      #3
      Re: Adding elements with concatination to an Array


      "Michael Winter" <m.winter@bluey onder.co.invali d> skrev i en meddelelse
      news:daqme.4197 1$G8.2808@text. news.blueyonder .co.uk...[color=blue]
      > On 29/05/2005 21:53, JS wrote:
      >[color=green]
      > > I am trying to add an element to an array like this:
      > >
      > > var ty = [99, 100];
      > > zz = "ty";
      > > var ab = null;
      > >
      > > zz+="[23]";
      > >
      > > ab = eval(zz);[/color]
      >
      > [snip]
      >
      > Simplifying that code, you get:
      >
      > var ty = [99, 100],
      > ab = eval('ty[23]');
      >
      > which can be simplifier further to:
      >
      > var ty = [99, 100],
      > ab = ty[23];
      >[/color]


      But I would like to use the concatination method, just to learn how it
      works. I was told that it should be possible to convert an array into a
      string that still holds the elements:

      var ty = [99, 100];
      zz = "ty";

      Then through zz, it should be possible to add elements to ty:

      zz+="[23]";

      that can be viewed through "ab":

      ab = eval(zz);
      document.write( ab.length);

      I know it seems silly, but I would just like to know what I am doing wrong,
      because this method should work.


      Comment

      • Lasse Reichstein Nielsen

        #4
        Re: Adding elements with concatination to an Array

        "JS" <dsa.@asdf.co m> writes:
        [color=blue][color=green][color=darkred]
        >> > zz = "ty";[/color][/color][/color]
        ....[color=blue][color=green][color=darkred]
        >> > zz+="[23]";
        >> >
        >> > ab = eval(zz);[/color][/color][/color]

        [color=blue]
        > But I would like to use the concatination method, just to learn how it
        > works.[/color]

        Concatentaing strings works fine, but it was never a good way to access
        values.
        [color=blue]
        > I was told that it should be possible to convert an array into a
        > string that still holds the elements:[/color]

        That, in itself, sounds ... misunderstood. Who told you that? If
        you have a link, I'd like to read it myself :)

        You are not turning a variable into a string, you merely make a string
        containing a variable name. Might as well let the variable point to
        the value instead of the name.
        [color=blue]
        > var ty = [99, 100];
        > zz = "ty";[/color]
        [color=blue]
        > Then through zz, it should be possible to add elements to ty:
        >
        > zz+="[23]";[/color]

        Appending the string "[23]" does not add any elements to anyting, but
        it does add characters to the string. If what you really want is
        to add the value "23" to the array currently referenced by the variable
        "ty", then the quickest way is:
        ty.push(23)
        or, for older browsers without a "push" method;
        ty[ty.length] = 23;
        [color=blue]
        > that can be viewed through "ab":
        >
        > ab = eval(zz);
        > document.write( ab.length);[/color]

        Here it seems you are assuming that evaluating the string will both
        1) append 23 to the array
        2) evaluate to a reference to that array.
        It does neither.

        The string you end up with is "ty[23]", there is nothing magic about string
        concatenation, so you get exactly what you ask for :)

        When evaluated, using "eval", it does exactly what the expression
        ty[23]
        would do: look up the value at index 23 of the array referenced by "ty".
        Since there is no such element, the resulting value is "undefined" . There
        is no assignment in that expression, so no change to any array.
        [color=blue]
        > I know it seems silly, but I would just like to know what I am doing wrong,
        > because this method should work.[/color]

        No, it shouldn't.

        Whatever you do using "eval" can also be done without it, and 99.9% of
        the time the alternative is shorter, safer, and less likely to blow up
        in your face.

        I could write something that would append a value to an array, using
        eval, but it has so many shortcommings that I fear writing it out,
        because someone might use it.


        /L 'ab=eval("["+ty+",23]");//DON'T EVER DO THIS!'
        --
        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

        • Richard Cornford

          #5
          Re: Adding elements with concatination to an Array

          JS wrote:[color=blue]
          > "Michael Winter" <m.winter@bluey onder.co.invali d> skrev i en
          > meddelelse news:daqme.4197 1$G8.2808@text. news.blueyonder .co.uk...[color=green]
          >> On 29/05/2005 21:53, JS wrote:[/color][/color]
          <snip>[color=blue][color=green][color=darkred]
          >>> zz+="[23]";
          >>>
          >>> ab = eval(zz);[/color]
          >>
          >> [snip]
          >>
          >> Simplifying that code, you get:
          >>
          >> var ty = [99, 100],
          >> ab = eval('ty[23]');
          >>
          >> which can be simplifier further to:
          >>
          >> var ty = [99, 100],
          >> ab = ty[23];[/color]
          >
          > But I would like to use the concatination method,[/color]

          Mike just showed you how to use the - concat - method of Arrays, your
          original code uses the compound assignment operator - += -, which is not
          necessarily a concatenation operator as its action depends on the type
          of its operands. And when it does concatenation it is string
          concatenation that it does.
          [color=blue]
          > just to learn how it works.[/color]

          It is unlikely that a compound assignment operator will 'work' in this
          context.
          [color=blue]
          > I was told that it should be possible to convert an
          > array into a string that still holds the elements:[/color]

          Whoever told you that is not a useful source of programming advice. You
          might just about get away with that sort of action if all of the
          elements are numeric or boolean, with considerable additional string
          manipulation.

          But you should observe the general javascript programming advice; if you
          think you need to use the - eval - function then the odds are that your
          code design is fundamentally wrong.
          [color=blue]
          > var ty = [99, 100];
          > zz = "ty";
          >
          > Then through zz, it should be possible to add elements to ty:
          >
          > zz+="[23]";[/color]

          As you are going to eval this you are building a string containing
          javascript source code. That string is "ty[23]", which is a bracket
          notation property accessor (something that you _never_ need to construct
          as a string and then eval).
          [color=blue]
          > that can be viewed through "ab":
          >
          > ab = eval(zz);[/color]

          The property accessor references the element of the array with the index
          23, but the array only has two elements so the "23" element is
          undefined.
          [color=blue]
          > document.write( ab.length);[/color]

          And assigning the value of an element in an array to a variable does not
          alter the length of an array.
          [color=blue]
          > I know it seems silly,[/color]

          Absolutly.
          [color=blue]
          > but I would just like to know what I am doing
          > wrong,[/color]

          Apparently you are listening to bad advice, ignoring good advice and
          failing to RTFM.
          [color=blue]
          > because this method should work.[/color]

          It does work, it is just that what it does (and should do) bares no
          relationship with your apparent intent.

          Richard.


          Comment

          • Lee

            #6
            Re: Adding elements with concatination to an Array

            JS said:
            [color=blue]
            >var ty = [99, 100];
            >zz = "ty";
            >
            >Then through zz, it should be possible to add elements to ty:
            >
            >zz+="[23]";
            >
            >that can be viewed through "ab":[/color]

            At this point, zz="ty[23]"
            [color=blue]
            >ab = eval(zz);[/color]

            Since ty doesn't contain an element with index 23,
            ab is now undefined.

            You could assign a value to it:

            eval(zz+"=101") ;
            alert(ty[23]);

            As a rule of thumb, if you find yourself using eval(), you've
            almost certainly overlooked a better way to accomplish your goal.

            Comment

            • RobG

              #7
              Re: Adding elements with concatination to an Array

              Lee wrote:[color=blue]
              > JS said:
              >
              >[color=green]
              >>var ty = [99, 100];
              >>zz = "ty";
              >>
              >>Then through zz, it should be possible to add elements to ty:
              >>
              >>zz+="[23]";
              >>
              >>that can be viewed through "ab":[/color]
              >
              >
              > At this point, zz="ty[23]"
              >
              >[color=green]
              >>ab = eval(zz);[/color]
              >
              >
              > Since ty doesn't contain an element with index 23,
              > ab is now undefined.
              >
              > You could assign a value to it:
              >
              > eval(zz+"=101") ;
              > alert(ty[23]);
              >[/color]

              Without commenting on 'eval', this puts the value '101' at index 23 of
              the array, effectively adding 21 empty elements. 'ty' is now:

              [99,100,,,,,,,,, ,,,,,,,,,,,,,10 1]

              The simple way to append elements is with:

              ty.push(23);

              the alternative where push is not supported is:

              ty[ty.length] = 23;

              which will result in ty looking like:

              [99,100,23]

              Which may be what the OP was after (or not...).


              --
              Rob

              Comment

              • Lee

                #8
                Re: Adding elements with concatination to an Array

                RobG said:[color=blue]
                >
                >Lee wrote:[color=green]
                >> JS said:
                >>
                >>[color=darkred]
                >>>var ty = [99, 100];
                >>>zz = "ty";
                >>>
                >>>Then through zz, it should be possible to add elements to ty:
                >>>
                >>>zz+="[23]";
                >>>
                >>>that can be viewed through "ab":[/color]
                >>
                >>
                >> At this point, zz="ty[23]"
                >>
                >>[color=darkred]
                >>>ab = eval(zz);[/color]
                >>
                >>
                >> Since ty doesn't contain an element with index 23,
                >> ab is now undefined.
                >>
                >> You could assign a value to it:
                >>
                >> eval(zz+"=101") ;
                >> alert(ty[23]);
                >>[/color]
                >
                > Without commenting on 'eval', this puts the value '101' at index 23 of
                > the array, effectively adding 21 empty elements. 'ty' is now:
                >
                > [99,100,,,,,,,,, ,,,,,,,,,,,,,10 1]
                >
                > The simple way to append elements is with:
                >
                > ty.push(23);
                >
                > the alternative where push is not supported is:
                >
                > ty[ty.length] = 23;
                >
                > which will result in ty looking like:
                >
                > [99,100,23]
                >
                > Which may be what the OP was after (or not...).[/color]

                Ok, I saw +="[23]" as trying to index location 23, but I agree now
                that he was trying to append an array literal.

                Comment

                • RobG

                  #9
                  Re: Adding elements with concatination to an Array

                  Lee wrote:[color=blue]
                  > RobG said:
                  >[color=green]
                  >>Lee wrote:
                  >>[color=darkred]
                  >>>JS said:
                  >>>
                  >>>
                  >>>
                  >>>>var ty = [99, 100];
                  >>>>zz = "ty";
                  >>>>
                  >>>>Then through zz, it should be possible to add elements to ty:
                  >>>>
                  >>>>zz+="[23]";
                  >>>>
                  >>>>that can be viewed through "ab":
                  >>>
                  >>>
                  >>>At this point, zz="ty[23]"
                  >>>
                  >>>
                  >>>
                  >>>>ab = eval(zz);
                  >>>
                  >>>
                  >>>Since ty doesn't contain an element with index 23,
                  >>>ab is now undefined.
                  >>>
                  >>>You could assign a value to it:
                  >>>
                  >>> eval(zz+"=101") ;
                  >>> alert(ty[23]);
                  >>>[/color]
                  >>
                  >> Without commenting on 'eval', this puts the value '101' at index 23 of
                  >> the array, effectively adding 21 empty elements. 'ty' is now:
                  >>
                  >> [99,100,,,,,,,,, ,,,,,,,,,,,,,10 1]
                  >>
                  >> The simple way to append elements is with:
                  >>
                  >> ty.push(23);
                  >>
                  >> the alternative where push is not supported is:
                  >>
                  >> ty[ty.length] = 23;
                  >>
                  >> which will result in ty looking like:
                  >>
                  >> [99,100,23]
                  >>
                  >> Which may be what the OP was after (or not...).[/color]
                  >
                  >
                  > Ok, I saw +="[23]" as trying to index location 23, but I agree now
                  > that he was trying to append an array literal.
                  >[/color]

                  What you had is probably a valid interpretation of the OP's request,
                  it's difficult to determine a poster's requirements in most cases - I'm
                  off-base perhaps 50% of the time (some may suggest a higher number...).
                  8-p


                  --
                  Rob

                  Comment

                  Working...