how to create an Array with parametrized name?

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

    #1

    how to create an Array with parametrized name?

    hello everybody,

    is there a way of creating an array with help of a function that would
    accept the name of this array as a parameter and then create global
    Array type variable of that name?
    so that for example the following code would work as well in browsers as
    under Windows Scripting Host:

    str = "tableA";

    fDoArray(str);
    fDoArray("table B");

    tableA[10] = 10;
    tableB[11] = 11;

    I would appreciate any suggestions and help,
    regards,
    mirek
  • lallous

    #2
    Re: how to create an Array with parametrized name?

    Hello,

    <script>
    function fDoArray(arrayN ame)
    {
    window[arrayName] = new Array();
    }

    str = "tableA";

    fDoArray(str);
    fDoArray("table B");

    tableA[10] = 10;
    tableB[11] = 11;

    alert(tableB);
    alert(tableA);
    </script>

    --
    Elias


    "nobody" <nobody@non.exi ste.nt> wrote in message
    news:b2GBb.2102 26$361.115205@n ews.chello.at.. .[color=blue]
    > hello everybody,
    >
    > is there a way of creating an array with help of a function that would
    > accept the name of this array as a parameter and then create global
    > Array type variable of that name?
    > so that for example the following code would work as well in browsers as
    > under Windows Scripting Host:
    >
    > str = "tableA";
    >
    > fDoArray(str);
    > fDoArray("table B");
    >
    > tableA[10] = 10;
    > tableB[11] = 11;
    >
    > I would appreciate any suggestions and help,
    > regards,
    > mirek[/color]


    Comment

    • Vjekoslav Begovic

      #3
      Re: how to create an Array with parametrized name?

      "nobody" <nobody@non.exi ste.nt> wrote:
      [color=blue]
      > is there a way of creating an array with help of a function that would
      > accept the name of this array as a parameter and then create global
      > Array type variable of that name?
      > so that for example the following code would work as well in browsers as
      > under Windows Scripting Host:
      >
      > str = "tableA";
      >
      > fDoArray(str);
      > fDoArray("table B");
      >
      > tableA[10] = 10;
      > tableB[11] = 11;[/color]

      function fDoArray(str){
      window[str]=new Array();
      return window[str];
      }


      Comment

      • nobody

        #4
        Re: how to create an Array with parametrized name?

        hello,

        thanks Vjekoslav and Elias. do you know any solution, that would also
        work under Windows Scripting Host?

        cheers,
        mirek

        Comment

        • Martin Honnen

          #5
          Re: how to create an Array with parametrized name?



          nobody wrote:
          [color=blue]
          > is there a way of creating an array with help of a function that would
          > accept the name of this array as a parameter and then create global
          > Array type variable of that name?
          > so that for example the following code would work as well in browsers as
          > under Windows Scripting Host:
          >
          > str = "tableA";
          >
          > fDoArray(str);
          > fDoArray("table B");
          >
          > tableA[10] = 10;
          > tableB[11] = 11;[/color]

          I think using this works as follows:


          function output (text) {
          if (typeof document != 'undefined' && typeof document.write !=
          'undefined') {
          document.write( text + '<br>\n');
          }
          else if (typeof WScript != 'undefined') {
          WScript.Echo(te xt);
          }
          }

          function createArray (variableName) {
          this[variableName] = [];
          }

          createArray('ar rayName');
          arrayName[0] = 'Kibo';
          arrayName[1] = 'Maho';

          output(arrayNam e);
          --

          Martin Honnen
          http://JavaScript.FAQTs.com/

          Comment

          • Douglas Crockford

            #6
            Re: how to create an Array with parametrized name?

            > thanks Vjekoslav and Elias. do you know any solution, that would also[color=blue]
            > work under Windows Scripting Host?[/color]

            The global object does not have a standard name, which is sort of surprising. In
            browsers, it can be referred to as 'window'. In other environments it might have
            no name at all.

            The 'this' variable, when used outside of any function, refers to the global
            object. So, at the top of your program, write

            var global = this;

            and then use 'global' in place of 'window'.



            Comment

            • nobody

              #7
              Re: how to create an Array with parametrized name?

              Martin and Douglas -- thank you both for help and WSH solution

              cheers :)
              mirek

              Comment

              • Joe Earnest

                #8
                Re: how to create an Array with parametrized name?

                Hi,

                "nobody" <nobody@non.exi ste.nt> wrote in message
                news:XBGBb.2105 76$361.202975@n ews.chello.at.. .
                | hello,
                |
                | thanks Vjekoslav and Elias. do you know any solution, that would also
                | work under Windows Scripting Host?

                original message:

                is there a way of creating an array with help of a function that would
                accept the name of this array as a parameter and then create global
                Array type variable of that name?
                so that for example the following code would work as well in browsers as
                under Windows Scripting Host:
                ---

                While you're looking for a JS solution, you may want to consider ...

                This is easy in VBS - not sure about JS. Although undocumented, the VBS
                Execute statement will create a new global variable (despite any Option
                Explicit statement), if it does not find the variable name referenced in
                either its immediate local variable list or the global variable list. So
                the following should work (air code):

                sub NewArray (rsArrayName)
                execute "dim " & rsArrayName & "()"
                end sub

                Just Redim after the call, as needed, or you could incorporate the
                dimensions and bounds through an additional string parameter, if you wish.
                You can wrap the code in On Error ... statements, if you're worried about
                potentially Dimming an existing array. You can mix JS and VBS in HTML or
                WSC wrappers.

                Joe Earnest



                ---
                Outgoing mail is certified Virus Free.
                Checked by AVG anti-virus system (http://www.grisoft.com).
                Version: 6.0.521 / Virus Database: 319 - Release Date: 09-23-03


                Comment

                • Bogdan Blaszczak

                  #9
                  Re: how to create an Array with parametrized name?

                  Uzytkownik "Douglas Crockford" <nospam@covad.n et> napisal w wiadomosci
                  news:73115$3fd7 44ba$44a4aede$1 0883@msgid.mega newsservers.com ...
                  ....[color=blue]
                  > The 'this' variable, when used outside of any function, refers to the[/color]
                  global[color=blue]
                  > object. So, at the top of your program, write
                  >
                  > var global = this;[/color]

                  using try...catch may cause the same code work both in browser and wsh.

                  var wsh
                  try{window=this ;wsh=1}catch(e) {}

                  function fDoArray(x){ret urn window[x]=[]}

                  fDoArray("table A")
                  tableA[0]=0
                  tableA[1]=1
                  tableA[2]=2

                  if(wsh){
                  Shell=WScript.C reateObject("WS cript.Shell")
                  Shell.Popup(tab leA)
                  }
                  else alert(tableA)

                  greets
                  BlaTek



                  Comment

                  • Gerry Hickman

                    #10
                    Re: how to create an Array with parametrized name?

                    Bogdan Blaszczak wrote:[color=blue]
                    > using try...catch may cause the same code work both in browser and wsh.
                    >
                    > var wsh
                    > try{window=this ;wsh=1}catch(e) {}[/color]

                    This may fail to give the right results if running under some other host
                    such as ASP. I'm trying to imagine the purpose of the original posters
                    request?

                    --
                    Gerry Hickman (London UK)

                    Comment

                    • nobody

                      #11
                      Re: how to create an Array with parametrized name?

                      Gerry Hickman wrote:
                      [color=blue]
                      > This may fail to give the right results if running under some other host
                      > such as ASP. I'm trying to imagine the purpose of the original posters
                      > request?[/color]

                      hello Gerry,

                      the purpose is as follows. I have a program that provides its own
                      scripting language. the scripting language is very powerful but lacks
                      sort of constructions which are natural in JS or VBS.
                      this program also allows cooperation with other applications through
                      Windows Automation Model (I'm not sure if it is that called). it also
                      provides the ability of using scripting languages via WSH, sharing,
                      importing, exporting their variables, using their functions etc.

                      the idea was to create array with parametrized name using JS. created
                      array with that special name would be returned to program's own
                      scripting language. here's a sketch of JS function that would do this.
                      LFA is the program's own function that do the trick. it puts
                      *prefix..postfi x* array into program's own script space like putting
                      book on a shelf.

                      function fDoArray( strArrayName, intNumber ) {
                      var str = "prefix" + strArrayName + intNumber + "postfix";
                      LFA(str) = new Array();
                      }

                      thanks for all responses,
                      cheers,
                      mirek

                      Comment

                      • Lasse Reichstein Nielsen

                        #12
                        Re: how to create an Array with parametrized name?

                        nobody <nobody@non.exi ste.nt> writes:
                        [color=blue]
                        > thanks Vjekoslav and Elias. do you know any solution, that would also
                        > work under Windows Scripting Host?[/color]

                        This should work in any ECMAScript compliant language:

                        function doArray(x) {
                        this[x]=[];
                        }

                        As long as you call the function directly, and not as a method of some
                        object, "this" refers to the global object.

                        I haven't tested it in the WSH, though, but if JScript is ECMAScript
                        compliant, it should work.

                        /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

                        • Al Dunbar   [MS-MVP]

                          #13
                          Re: how to create an Array with parametrized name?


                          "Joe Earnest" <joeearnestNO@S PAMqwest.netPLE ASE> wrote in message
                          news:uvbGulzvDH A.2448@TK2MSFTN GP09.phx.gbl...[color=blue]
                          > Hi,
                          >
                          > "nobody" <nobody@non.exi ste.nt> wrote in message
                          > news:XBGBb.2105 76$361.202975@n ews.chello.at.. .
                          > | hello,
                          > |
                          > | thanks Vjekoslav and Elias. do you know any solution, that would also
                          > | work under Windows Scripting Host?
                          >
                          > original message:
                          >
                          > is there a way of creating an array with help of a function that would
                          > accept the name of this array as a parameter and then create global
                          > Array type variable of that name?
                          > so that for example the following code would work as well in browsers as
                          > under Windows Scripting Host:
                          > ---
                          >
                          > While you're looking for a JS solution, you may want to consider ...
                          >
                          > This is easy in VBS - not sure about JS. Although undocumented, the VBS
                          > Execute statement[/color]

                          Time to download more up to date docs, Joe. Mine has the following:


                          Execute Statement
                          See Also
                          Eval Function | ExecuteGlobal Statement

                          Requirements
                          Version 1

                          Executes one or more specified statements.

                          Execute statementThe required statement argument is a string expression
                          containing one or more statements for execution. Include multiple statements
                          in the statement argument, using colons or embedded line breaks to separate
                          them.
                          [color=blue]
                          > will create a new global variable (despite any Option
                          > Explicit statement), if it does not find the variable name referenced in
                          > either its immediate local variable list or the global variable list. So
                          > the following should work (air code):
                          >
                          > sub NewArray (rsArrayName)
                          > execute "dim " & rsArrayName & "()"
                          > end sub
                          >
                          > Just Redim after the call, as needed, or you could incorporate the
                          > dimensions and bounds through an additional string parameter, if you wish.
                          > You can wrap the code in On Error ... statements, if you're worried about
                          > potentially Dimming an existing array. You can mix JS and VBS in HTML or
                          > WSC wrappers.[/color]

                          A similar approach can be used to define global constants in a similar
                          manner from within a routine.

                          /Al


                          Comment

                          • Joe Earnest

                            #14
                            Re: how to create an Array with parametrized name?

                            Hi Al,

                            [snipped]

                            "Al Dunbar [MS-MVP]" <Alan-no-Drub-spam@hotmail.co m> wrote in message
                            news:OiXCfn5vDH A.3416@tk2msftn gp13.phx.gbl...
                            | Time to download more up to date docs, Joe. Mine has the following:

                            The function is documented, but it's the fact that it circumvents Option
                            Explicit and creates a new variable instead of erroring out that's
                            undocumented and unintended. That's the only reason that it would work for
                            the OP in this situation and in the example that I gave. When I first
                            stumbled on this behavior over a year ago, Michael Harris verified the
                            operation and verified with Eric Lippert (who apparently wrote the execute
                            code) that the behavior is both unintended and unlikely to change.



                            (from MH post)

                            "I checked with Eric Lippert (who wrote the Execute and ExecuteGlobal
                            implementation code)...

                            What you observe is actually a bug and unintended behavior. Execute within
                            a procedure is *not* supposed to create a variable with global scope. He
                            also noted that this is probably something that will never get fixed ;-)..."


                            Regards,
                            Joe Earnest



                            ---
                            Outgoing mail is certified Virus Free.
                            Checked by AVG anti-virus system (http://www.grisoft.com).
                            Version: 6.0.521 / Virus Database: 319 - Release Date: 09-23-03


                            Comment

                            • Al Dunbar   [MS-MVP]

                              #15
                              Re: how to create an Array with parametrized name?


                              "Joe Earnest" <joeearnestNO@S PAMqwest.netPLE ASE> wrote in message
                              news:OlkJZb6vDH A.1424@tk2msftn gp13.phx.gbl...[color=blue]
                              > Hi Al,
                              >
                              > [snipped]
                              >
                              > "Al Dunbar [MS-MVP]" <Alan-no-Drub-spam@hotmail.co m> wrote in message
                              > news:OiXCfn5vDH A.3416@tk2msftn gp13.phx.gbl...
                              > | Time to download more up to date docs, Joe. Mine has the following:
                              >
                              > The function is documented,[/color]

                              Ah, you didn't mean "undocument ed", but "not FULLY documented".
                              [color=blue]
                              > but it's the fact that it circumvents Option
                              > Explicit[/color]

                              Not really - see way below...
                              [color=blue]
                              > and creates a new variable[/color]

                              .... as I would expect a DIM statement to do ...
                              [color=blue]
                              > instead of erroring out[/color]

                              .... now *that* would be unexpected...
                              [color=blue]
                              > that's
                              > undocumented[/color]

                              .... granted. By the same token the "function" and "sub" statements are not
                              fully documented because they do not define all of the behaviours and side
                              effects that could result from their use. But I digress...
                              [color=blue]
                              > and unintended.[/color]

                              That's *their* problem. A more important question is: "Is it *expected*" to
                              which my answer is "Yes". A secondary question is: "will this departure from
                              a <fixed source> model be completely straightforward ", to which my answer is
                              "obviously not".
                              [color=blue]
                              > That's the only reason that it would work for
                              > the OP in this situation and in the example that I gave.[/color]

                              .... the reason it works is, well, that is how it works. It doesn't work
                              because it is a bug, but because the underlying code does what it does. The
                              fact that this was unintended by the developers is really beside the point.
                              [color=blue]
                              > When I first
                              > stumbled on this behavior over a year ago, Michael Harris verified the
                              > operation and verified with Eric Lippert (who apparently wrote the execute
                              > code) that the behavior is both unintended and unlikely to change.[/color]

                              Unintended: their mistake; unlikely to change: score one for platform
                              stability.
                              [color=blue]
                              >[/color]
                              http://www.google.com/groups?hl=en&l...961d93f&rnum=1[color=blue]
                              >
                              > (from MH post)
                              >
                              > "I checked with Eric Lippert (who wrote the Execute and ExecuteGlobal
                              > implementation code)...
                              >
                              > What you observe is actually a bug and unintended behavior.[/color]

                              I disagree :-) It is only a bug if the behaviour was intended NOT to
                              happen. Just because they missed a side effect of their own code (especially
                              one that has some specific uses), they should not go dissing themselves over
                              their oversight ;-)
                              [color=blue]
                              > Execute within
                              > a procedure is *not* supposed to create a variable with global scope. He
                              > also noted that this is probably something that will never get fixed[/color]
                              ;-)..."

                              I consider the related documentation to be in error (or at least misleading)
                              in this respect, probably because it was written before executeglobal was
                              implemented. One specific error in the definition of executeglobal is shown
                              in the extract below, highlighted in ALL CAPS.

                              I believe the paragraph and disbelieve the endline comments, both because
                              that makes sense based on what EXECUTEGLOBAL means, and because, well, that
                              is actually how it works. This also indicates that the writers of the
                              documentation were, like me, of the opinion that it was *expected* to create
                              a variable with global scope.

                              Nevertheless, the Option Explicit documentation states: "When you use the
                              Option Explicit statement, you must explicitly declare all variables using
                              the Dim, Private, Public, or ReDim statements. If you attempt to use an
                              undeclared variable name, an error occurs.". If you execute a DIM statement
                              with an EXECUTEGLOBAL statement, are you not explicitly declaring the
                              variable? It is true that this may appear less *explicit* a declaration when
                              reading through the code, as it could be obfuscated in many ways.

                              If, as implied, the executeglobal statement was never intended to modify the
                              global namespace, then what on earth was it supposed to do that execute by
                              itself could not?

                              The way I see it is that the developers implemented the Executeglobal
                              statement to do what it implies (to me at least): execute code as if it was
                              being executed in the global scope of the script. The fact that it does this
                              to such a great extent even when that was not their conscious intent speaks
                              to the quality of their work.

                              /Al

                              <extract>

                              Adding procedures and classes at runtime can be useful, but also introduces
                              the possibility of OVERWRITING EXISTING GLOBAL VARIABLEs and functions at
                              runtime. Because this can cause significant programming problems, CARE
                              SHOULD BE EXERCISED when using the ExecuteGlobal statement. If you DON'T
                              need access to a variable or function outside of a procedure, USE THE
                              EXECUTE STATEMENT that will ONLY AFFECT THE NAMESPACE of the calling
                              function.

                              The following example illustrates the use of the ExecuteGlobal statement:

                              Dim X ' Declare X in global scope.
                              X = "Global" ' Assign global X a value.
                              Sub Proc1 ' Declare procedure.
                              Dim X ' Declare X in local scope.
                              X = "Local" ' Assign local X a value.
                              ' The Execute statement here creates a
                              ' procedure that, when invoked, prints X.
                              ' It print the global X because Proc2
                              ' inherits everything in global scope.
                              ExecuteGlobal "Sub Proc2: Print X: End Sub"
                              Print Eval("X") ' Print local X.
                              Proc2 ' Invoke Proc2 in Global scope resulting
                              ' in "Global" being printed.
                              End Sub
                              PROC2 ' THIS LINE CAUSES AN ERROR SINCE
                              ' PROC2 IS UNAVAILABLE OUTSIDE PROC1.

                              [THIS IS EXACTLY THE OPPOSITE OF WHAT THE FIRST PARAGRAPH SAID. THAT COMMENT
                              WOULD APPLY HAD THE PROCEDURE USE EXECUTE INSTEAD OF EXECUTEGLOBAL]

                              Proc1 ' Invoke Proc1.
                              Execute "Sub Proc2: Print X: End Sub"
                              Proc2 ' This invocation succeeds because Proc2
                              ' is now available globally.

                              </extract>


                              Comment

                              Working...