Click to See Complete Forum and Search --> : Using a variable from a function


jshowe
07-17-2003, 06:26 PM
Hi,
I think I am trying to figure out how to make a global variable. I have a variable array1.length in a function and I need to access it outside the function... Any ideas other then a return?
Thanks
-Scott

Khalid Ali
07-17-2003, 06:35 PM
<script type="text/javascript">

//global variable
var len =0;

function someFunc(){
var array1 = new Array(0,1,2,3,4,5,6,7,8,9);
//set global variable's value to that of arrays length
len = array1.length;
}

len can be used anywahere now..but make sure before len is used someFunc() is called

said_fox
07-19-2003, 04:40 PM
Look at this code

<html>
<head>
<script>
var x = "green";
function mycolor() {

x = prompt("enter the color name","");
}
</script>
</head>
<body onload="mycolor()">
<script>
document.write("the color is "+x);
</script>
</body>
</html>



The document.write always print x as green, ever the value that I eneterd is?

:confused:
So How Can the value of Global Variable x be changed?:confused: :confused: :(

David Harrison
07-19-2003, 04:59 PM
Like I said, in the other thread, the global variable x is only changed when the function is run and since the function is run onload, it is created too late.

This script would change the variable:

<html>
<head>
<title>Global Variable In Function</title>
<script type="text/javascript">
var x = "green";
function mycolor() {
x = prompt("enter the color name","");
}
mycolor();
</script>
</head>
<body>
<script type="text/javascript">
document.write("the color is "+x);
</script>
</body>
</html>

jshowe
07-21-2003, 03:09 PM
Why did you call the function mycolor() in the script itself? Does that do something different then putting it somewhere in the body?

David Harrison
07-21-2003, 03:31 PM
I could just as easily done this:

<html>
<head>
<title>Global Variable In Function</title>
<script type="text/javascript"><!--
var x = "green";
function mycolor(){
x = prompt("enter the color name","");
}
//--></script>
</head>
<body>
<script type="text/javascript"><!--
mycolor();
document.write("the color is "+x);
//--></script>
</body>
</html>

But as long as I don't do this:

<body onload="mycolor();">

the script will be valid.

Edit: To find out why putting it into onload is wrong see this thread (http://forums.webdeveloper.com/showthread.php?s=&threadid=13395).