Sign In | Register Now About Bytes | Help | Site Map
Connecting Tech Pros Worldwide

Create Global Var in Function

Question posted by: Andrew V. Romero (Guest) on July 20th, 2005 09:07 AM
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="JavaScript">

var variablesInUrl;
var vArray = new Array();

function loadUrlVariables()
{
varString = location.search;
//removes ? from varString
varString = varString.substring(1,varString.length);
//split into array containing variable=value
variableArray = varString.split('&');
variablesInUrl = variableArray.length-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(varName)
{
for (i=0; i<=variablesInUrl; i++)
{
if (vArray[i][0] == varName)
return vArray[i][1]
}
alert ("Variable: "+varName+" was not found.")
}

loadUrlVariables()

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

</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
loadUrlVariables 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
loadUrlVariables I put
var testGlobal = document.body
testGlobal = "Am I a Global Variable"

then after my other alert, I did alert(testGlobal), 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's Avatar
Andrew V. Romero
Guest
n/a Posts
July 20th, 2005
09:07 AM
#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="JavaScript">
>
> var variablesInUrl;
> var vArray = new Array();
>
> function loadUrlVariables()
> {
> varString = location.search;
> //removes ? from varString
> varString = varString.substring(1,varString.length);
> //split into array containing variable=value
> variableArray = varString.split('&');
> variablesInUrl = variableArray.length-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(varName)
> {
> for (i=0; i<=variablesInUrl; i++)
> {
> if (vArray[i][0] == varName)
> return vArray[i][1]
> }
> alert ("Variable: "+varName+" was not found.")
> }
>
> loadUrlVariables()
>
> //get value of a variable named step
> alert( getValue("weight") )
>
> </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
> loadUrlVariables 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
> loadUrlVariables I put
> var testGlobal = document.body
> testGlobal = "Am I a Global Variable"
>
> then after my other alert, I did alert(testGlobal), 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]


kaeli's Avatar
kaeli
Guest
n/a Posts
July 20th, 2005
09:07 AM
#3

Re: Create Global Var in Function
In article <3F12EA86.9080001@icqmail.com>, Join Bytes!
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(location.search.indexOf("?")+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.
http://www.ipwebdesign.net/kaelisSp...l_parseUrl.html

--
-------------------------------------------------
~kaeli~
There is no justification or rationalization
for mutilation. Ban declawing as inhumane.
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace
-------------------------------------------------

Lasse Reichstein Nielsen's Avatar
Lasse Reichstein Nielsen
Guest
n/a Posts
July 20th, 2005
09:07 AM
#4

Re: Create Global Var in Function
"Andrew V. Romero" <rrstudio2@icqmail.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="JavaScript">[/color]

<script type="text/javascript">

In HTML 4, the language attribute is deprecated, and the type
attribute is mandatory
[color=blue]
> variablesInUrl = variableArray.length-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
> loadUrlVariables 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
> loadUrlVariables 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(testGlobal), 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 loadURLVariables() {
var searchPairs = location.search.substring(1).split("&");
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 "loadURLVariables()" 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 - Join Bytes!
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'

Andrew V. Romero's Avatar
Andrew V. Romero
Guest
n/a Posts
July 20th, 2005
09:11 AM
#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@icqmail.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="JavaScript">[/color]
>
>
> <script type="text/javascript">
>
> In HTML 4, the language attribute is deprecated, and the type
> attribute is mandatory
>
>[color=green]
>> variablesInUrl = variableArray.length-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
>>loadUrlVariables 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
>>loadUrlVariables 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(testGlobal), 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 loadURLVariables() {
> var searchPairs = location.search.substring(1).split("&");
> 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 "loadURLVariables()" 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]


 
Not the answer you were looking for? Post your question . . .
189,325 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

Latest Articles: Read & Comment
  • Didn't find the answer you were looking for?
    Post Your Question
  • Top Community Contributors