create global variable from inside the function?

R

Ralph

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
 
R

RobG

Ralph said:
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.

function (){
window.anArray = ['foo', 'bar', 1, 2, 3];
}

Maybe you'd prefer:

var _global = this;
function (){
_global.anArray = ['foo', 'bar', 1, 2, 3];
}


It is a good idea to avoid global variables where possible, make them
properties of some other object - a kind of namespace to keep your
stuff from colliding with other stuff.
 
A

ASM

Ralph a écrit :
Hi

Is this possible?

var c = 'bonjour';

function glob() {
var a = 'hello';
b = 'saluti';
}

glob();

alert(a); // undefined
alert(b); // saluti
alert(c); // bonjour

all variables in JS are global
except those declared in a function and prefixed with var
One thing I can do is create the global array

do you mean array of globals ?
and add the new item to it
from inside the function but that's not what I'm looking for.

function arr() {
tablo = new Array('one','two');
}
function arrAdd() {
if( typeof (tablo) == 'undefined') arr();
for(var i=0; i<arguments.length; i++)
tablo[tablo.length] = arguments;
}

arrAdd('three','for','five');

alert(tablo[4]); // five
 
R

Ralph

ASM said:
Ralph a écrit :
Hi

Is this possible?

var c = 'bonjour';

function glob() {
var a = 'hello';
b = 'saluti';
}

glob();

alert(a); // undefined
alert(b); // saluti
alert(c); // bonjour

all variables in JS are global
except those declared in a function and prefixed with var
One thing I can do is create the global array

do you mean array of globals ?
and add the new item to it from inside the function but that's not
what I'm looking for.

function arr() {
tablo = new Array('one','two');
}
function arrAdd() {
if( typeof (tablo) == 'undefined') arr();
for(var i=0; i<arguments.length; i++)
tablo[tablo.length] = arguments;
}

arrAdd('three','for','five');

alert(tablo[4]); // five

Thank you all. That what I was looking for.
Ralph
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top