473,320 Members | 1,845 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

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="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

Jul 20 '05 #1
4 24140
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:
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


Jul 20 '05 #2
In article <3F**************@icqmail.com>, rr*******@icqmail.com
enlightened us with...
I have been working on a function which makes it easier for me to pull
variables from the URL. So far I have:


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/kaelisSpa..._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
-------------------------------------------------
Jul 20 '05 #3
"Andrew V. Romero" <rr*******@icqmail.com> writes:
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">
<script type="text/javascript">

In HTML 4, the language attribute is deprecated, and the type
attribute is mandatory
variablesInUrl = variableArray.length-1
bad naming, since there are "variableArray.length" variables in the URL,
not one less.

.... 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.
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).
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
"var" declares a local variable if used inside a function. It declares
a global variable if used outside of a function.
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?
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.
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?


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 - lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
Thanks everyone for the comments, they have really helped get me over
this hurdle in Javascript.

Lasse Reichstein Nielsen wrote:
"Andrew V. Romero" <rr*******@icqmail.com> writes:

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">

<script type="text/javascript">

In HTML 4, the language attribute is deprecated, and the type
attribute is mandatory

variablesInUrl = variableArray.length-1

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

...
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.

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).

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

"var" declares a local variable if used inside a function. It declares
a global variable if used outside of a function.

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?

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.

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?

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


Jul 20 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: lkrubner | last post by:
I have a webserver through Rackspace. I create a domain. I create an FTP user. I upload some files. I create a database called testOfSetupScript and then I create a database user named setup. I...
22
by: nobody | last post by:
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...
8
by: Steve Neill | last post by:
Can anyone suggest how to create an arbitrary object at runtime WITHOUT using the deprecated eval() function. The eval() method works ok (see below), but is not ideal. function Client() { }...
2
by: Chris LaJoie | last post by:
The code below creates a thread on a global function (ReadChildOutput): CreateThread(NULL, 0, ReadChildOutput, (LPVOID)this, 0, &ThreadId); How would I create a thread on a non-global function,...
2
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is...
3
by: Ralph | last post by:
Hi Is this possible? One thing I can do is create the global array and add the new item to it from inside the function but that's not what I'm looking for. Thank you Ralph
4
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is...
3
by: Beamer | last post by:
Hi I am trying to build a roating slide effect in javascript. Basically, I have a list like below <ul id="slideShowCnt"> <li id="slide0"><img .../></li> <li id="slide0"><img .../></li> <li...
17
by: DeZZar | last post by:
Hi all, I need to regularly backup my database as an Excel file and have been using the File Export option. Problem is I need anyone using the database to be able to do this easily - nopt...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.