Create Global Var in Function

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew V. Romero

    Create Global Var in Function

    I have been working on a function which makes it easier for me to pull
    variables from the URL. So far I have:
    <script language="JavaS cript">

    var variablesInUrl;
    var vArray = new Array();

    function loadUrlVariable s()
    {
    varString = location.search ;
    //removes ? from varString
    varString = varString.subst ring(1,varStrin g.length);
    //split into array containing variable=value
    variableArray = varString.split ('&');
    variablesInUrl = variableArray.l ength-1

    for (i=0; i<= variablesInUrl ; i++)
    {
    temp = variableArray[i].split("=");
    vArray[i] = new Array();
    vArray[i][0] = temp[0];
    vArray[i][1] = temp[1];
    }
    }

    //function returns variable's value
    function getValue(varNam e)
    {
    for (i=0; i<=variablesInU rl; i++)
    {
    if (vArray[i][0] == varName)
    return vArray[i][1]
    }
    alert ("Variable: "+varName+" was not found.")
    }

    loadUrlVariable s()

    //get value of a variable named step
    alert( getValue("weigh t") )

    </script>

    This works but in order to get the value of the variable, I have to use
    the getValue function. What I would really like is for the
    loadUrlVariable s function to create global variables out of the
    variables present in the URL. This way I could just access them
    normally (i.e. alert(weight) would display the value in the variable
    weight). I was reading some and tried a test. Inside of the
    loadUrlVariable s I put
    var testGlobal = document.body
    testGlobal = "Am I a Global Variable"

    then after my other alert, I did alert(testGloba l), but I got an
    testGlobal is undefined error. So how do I make a global variable from
    inside a function?

    On an unrelated note:
    In javascript, after each line are you suppose to put a ;? I see some
    scripts that have a semi colon after each line and some that don't. I
    haven't notice that it makes any different, but am wondering what the
    technically right way is to do it?

    Thanks,
    Andrew V. Romero

  • Andrew V. Romero

    #2
    Re: Create Global Var in Function

    I should have mentioned that I would like the function to create global
    variables out of each variable in the URL automatically. So I want
    vArray[i][0] to be the name of the first global variable and
    vArray[i][1] to be its value, etc. Let's pretend I don't know the names
    of the variables before hand (i.e. I can not just say
    weight=vArray[i][1]. I am aware of the possible naming conflicts that
    may arise due to this.

    Thanks,
    Andrew V. Romero

    Andrew V. Romero wrote:[color=blue]
    > I have been working on a function which makes it easier for me to pull
    > variables from the URL. So far I have:
    > <script language="JavaS cript">
    >
    > var variablesInUrl;
    > var vArray = new Array();
    >
    > function loadUrlVariable s()
    > {
    > varString = location.search ;
    > //removes ? from varString
    > varString = varString.subst ring(1,varStrin g.length);
    > //split into array containing variable=value
    > variableArray = varString.split ('&');
    > variablesInUrl = variableArray.l ength-1
    >
    > for (i=0; i<= variablesInUrl ; i++)
    > {
    > temp = variableArray[i].split("=");
    > vArray[i] = new Array();
    > vArray[i][0] = temp[0];
    > vArray[i][1] = temp[1];
    > }
    > }
    >
    > //function returns variable's value
    > function getValue(varNam e)
    > {
    > for (i=0; i<=variablesInU rl; i++)
    > {
    > if (vArray[i][0] == varName)
    > return vArray[i][1]
    > }
    > alert ("Variable: "+varName+" was not found.")
    > }
    >
    > loadUrlVariable s()
    >
    > //get value of a variable named step
    > alert( getValue("weigh t") )
    >
    > </script>
    >
    > This works but in order to get the value of the variable, I have to use
    > the getValue function. What I would really like is for the
    > loadUrlVariable s function to create global variables out of the
    > variables present in the URL. This way I could just access them
    > normally (i.e. alert(weight) would display the value in the variable
    > weight). I was reading some and tried a test. Inside of the
    > loadUrlVariable s I put
    > var testGlobal = document.body
    > testGlobal = "Am I a Global Variable"
    >
    > then after my other alert, I did alert(testGloba l), but I got an
    > testGlobal is undefined error. So how do I make a global variable from
    > inside a function?
    >
    > On an unrelated note:
    > In javascript, after each line are you suppose to put a ;? I see
    > some scripts that have a semi colon after each line and some that
    > don't. I haven't notice that it makes any different, but am wondering
    > what the technically right way is to do it?
    >
    > Thanks,
    > Andrew V. Romero
    >[/color]

    Comment

    • kaeli

      #3
      Re: Create Global Var in Function

      In article <3F12EA86.90800 01@icqmail.com> , rrstudio2@icqma il.com
      enlightened us with...[color=blue]
      > I have been working on a function which makes it easier for me to pull
      > variables from the URL. So far I have:[/color]

      Use this technique. It's easier to get them when you want them.

      var paramArray = new Array();

      function getParams()
      {
      // split the query string into param=val pieces
      var qs = location.search .substr(locatio n.search.indexO f("?")+1);
      qs = qs.split("&");
      // split param and value into individual pieces
      for (var i=0; i<qs.length; i++)
      {
      tmp = qs[i].split("=");
      paramArray[tmp[0]] = tmp[1];
      }
      }

      Now you can just do paramArray["myParam"] to get the value of myParam.
      See example here.


      --
      -------------------------------------------------
      ~kaeli~
      There is no justification or rationalization
      for mutilation. Ban declawing as inhumane.


      -------------------------------------------------

      Comment

      • Lasse Reichstein Nielsen

        #4
        Re: Create Global Var in Function

        "Andrew V. Romero" <rrstudio2@icqm ail.com> writes:
        [color=blue]
        > I have been working on a function which makes it easier for me to pull
        > variables from the URL. So far I have:
        >
        > <script language="JavaS cript">[/color]

        <script type="text/javascript">

        In HTML 4, the language attribute is deprecated, and the type
        attribute is mandatory
        [color=blue]
        > variablesInUrl = variableArray.l ength-1[/color]

        bad naming, since there are "variableArray. length" variables in the URL,
        not one less.

        ....[color=blue]
        > This works but in order to get the value of the variable, I have to
        > use the getValue function. What I would really like is for the
        > loadUrlVariable s function to create global variables out of the
        > variables present in the URL.[/color]

        Don't do that. Creating global variables gives too big a chance of
        overwriting something important (e.g., if one of the variables
        was called "window" or "document", then you would be in trouble).
        [color=blue]
        > This way I could just access them
        > normally (i.e. alert(weight) would display the value in the variable
        > weight). I was reading some and tried a test. Inside of the
        > loadUrlVariable s I put
        >
        > var testGlobal = document.body[/color]

        "var" declares a local variable if used inside a function. It declares
        a global variable if used outside of a function.
        [color=blue]
        > testGlobal = "Am I a Global Variable"
        >
        > then after my other alert, I did alert(testGloba l), but I got an
        > testGlobal is undefined error. So how do I make a global variable
        > from inside a function?[/color]

        You don't write "var" in front.

        If you just write:

        foo = 42;

        and "foo" is not declared as a local variable, then it will be created
        as a global variable.

        You can also create global variables as properties of the global object.
        The global variable "window" is a reference to the global object, so writing

        window["foo"] = 42;

        will also create a global variable called "foo".


        Still, I suggest that you create just one global variable and use
        the to store the rest:

        ---

        var variables={}; // global variable referencing empty object
        function loadURLVariable s() {
        var searchPairs = location.search .substring(1).s plit("&");
        for (var i in searchPairs) {
        var pair = searchPairs[i].split("=");
        variables[pair[0]]=unescape(pair[1].replace(/\+/g," "));
        /* if this is the result of a form action */
        }
        }

        ---

        Then you can run "loadURLVariabl es()" and afterwards, you can refer to the
        variables as

        variables.foo

        or

        variables["foo"]

        without clobbering the global scope with too many variables.
        [color=blue]
        > On an unrelated note:
        > In javascript, after each line are you suppose to put a ;? I
        > see some scripts that have a semi colon after each line and
        > some that don't. I haven't notice that it makes any
        > different, but am wondering what the technically right way is
        > to do it?[/color]

        Each statement ends in a semicolon, but in some cases the semicolon can
        be omitted and is then automatically inserted by the Javascript parser.
        That is called "semicolon insertion". In other cases, omitting the
        semicolon gives an error.

        In practice, it is much simpler *and safer* not to worry about it, and
        *always* end ones statements with a semicolon, and not let statements
        spanning more than one line have lines ending where a semicolon would
        make sense.

        /L
        --
        Lasse Reichstein Nielsen - lrn@hotpop.com
        Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit. html>
        'Faith without judgement merely degrades the spirit divine.'

        Comment

        • Andrew V. Romero

          #5
          Re: Create Global Var in Function

          Thanks everyone for the comments, they have really helped get me over
          this hurdle in Javascript.

          Lasse Reichstein Nielsen wrote:[color=blue]
          > "Andrew V. Romero" <rrstudio2@icqm ail.com> writes:
          >
          >[color=green]
          >>I have been working on a function which makes it easier for me to pull
          >>variables from the URL. So far I have:
          >>
          >><script language="JavaS cript">[/color]
          >
          >
          > <script type="text/javascript">
          >
          > In HTML 4, the language attribute is deprecated, and the type
          > attribute is mandatory
          >
          >[color=green]
          >> variablesInUrl = variableArray.l ength-1[/color]
          >
          >
          > bad naming, since there are "variableArray. length" variables in the URL,
          > not one less.
          >
          > ...
          >[color=green]
          >>This works but in order to get the value of the variable, I have to
          >>use the getValue function. What I would really like is for the
          >>loadUrlVariab les function to create global variables out of the
          >>variables present in the URL.[/color]
          >
          >
          > Don't do that. Creating global variables gives too big a chance of
          > overwriting something important (e.g., if one of the variables
          > was called "window" or "document", then you would be in trouble).
          >
          >[color=green]
          >>This way I could just access them
          >>normally (i.e. alert(weight) would display the value in the variable
          >>weight). I was reading some and tried a test. Inside of the
          >>loadUrlVariab les I put
          >>
          >>var testGlobal = document.body[/color]
          >
          >
          > "var" declares a local variable if used inside a function. It declares
          > a global variable if used outside of a function.
          >
          >[color=green]
          >>testGlobal = "Am I a Global Variable"
          >>
          >>then after my other alert, I did alert(testGloba l), but I got an
          >>testGlobal is undefined error. So how do I make a global variable
          >>from inside a function?[/color]
          >
          >
          > You don't write "var" in front.
          >
          > If you just write:
          >
          > foo = 42;
          >
          > and "foo" is not declared as a local variable, then it will be created
          > as a global variable.
          >
          > You can also create global variables as properties of the global object.
          > The global variable "window" is a reference to the global object, so writing
          >
          > window["foo"] = 42;
          >
          > will also create a global variable called "foo".
          >
          >
          > Still, I suggest that you create just one global variable and use
          > the to store the rest:
          >
          > ---
          >
          > var variables={}; // global variable referencing empty object
          > function loadURLVariable s() {
          > var searchPairs = location.search .substring(1).s plit("&");
          > for (var i in searchPairs) {
          > var pair = searchPairs[i].split("=");
          > variables[pair[0]]=unescape(pair[1].replace(/\+/g," "));
          > /* if this is the result of a form action */
          > }
          > }
          >
          > ---
          >
          > Then you can run "loadURLVariabl es()" and afterwards, you can refer to the
          > variables as
          >
          > variables.foo
          >
          > or
          >
          > variables["foo"]
          >
          > without clobbering the global scope with too many variables.
          >
          >[color=green]
          >>On an unrelated note:
          >> In javascript, after each line are you suppose to put a ;? I
          >> see some scripts that have a semi colon after each line and
          >> some that don't. I haven't notice that it makes any
          >> different, but am wondering what the technically right way is
          >> to do it?[/color]
          >
          >
          > Each statement ends in a semicolon, but in some cases the semicolon can
          > be omitted and is then automatically inserted by the Javascript parser.
          > That is called "semicolon insertion". In other cases, omitting the
          > semicolon gives an error.
          >
          > In practice, it is much simpler *and safer* not to worry about it, and
          > *always* end ones statements with a semicolon, and not let statements
          > spanning more than one line have lines ending where a semicolon would
          > make sense.
          >
          > /L[/color]

          Comment

          Working...