PDA

View Full Version : Function makes array, then access array outside of function?


jeffcool
02-26-2004, 03:51 PM
don't know if this is a newbie question, or I'm just doing something stupid.. but what I have is a function that has a loop in it that created an array.


this.onLoad = make_Array;
function make_Array() {
X = 5;
var my_Array:Array = new Array();
for (n=0; n<X; n++) {
my_Array[n] = n;
}
//show the array I just created
trace("Display Array:");
for (n=0; n<X; n++) {
trace(my_Array[n]);
}
}
//now outside the loop I want to show it again
trace("Display Array Again:");
for (n=0; n<X; n++) {
trace(my_Array[n]);
}
my output in the trace window is:
Display Array Again:
Display Array:
0
1
2
3
4

Why does the second display get done before the first?

divarch
02-27-2004, 03:53 AM
Just make some small changes to your script.

make_Array();//call the function like that, not 'this.onLoad=...'
function make_Array() {
X = 5;
my_Array = new Array();//don't use 'var' keyword, so variable is accessible outside, also U can use '_global.my_Array'
for (n=0; n<X; n++) {
my_Array[n] = n;
}
//show the array I just created
trace("Display Array:");
for (n=0; n<X; n++) {
trace(my_Array[n]);
}
}
trace("Display Array Again:");
for (n=0; n<X; n++) {
trace(my_Array[n]);
}//it works now


Cheers

subbusos
02-27-2004, 06:01 AM
Hi....

Plz. have this in mind always...

Whenever you are declaring a variable or an array or an object inside a function, using 'var' statement, then that variable is local to that function only and will get deleted at the end of the execution of the function. So, declare the variables outside the function, if you want to access it from outside.

e.g. 1
function makeArray() {
var x = new Array(1, 2, 3, 4, 5);
}
trace(x);

In the above case, the var x is existent only inside the function.

e.g. 2
var x = new Array();
function makeArray() {
for (var i = 0; i<5; i++) {
x[i] = i+1;
}
}
makeArray()
trace(x);

In the above case, you can access the array you have already declared.

jeffcool
02-27-2004, 02:13 PM
Thanks for the help. This make s a lot more since to me now!

- Jeff