Hello there, I am trying to create a new global variable in a function with a custom name.
I need something like this:
function newVariable(name){
createVariableWithName(name);
}
Printable View
Hello there, I am trying to create a new global variable in a function with a custom name.
I need something like this:
function newVariable(name){
createVariableWithName(name);
}
I don't think that is possible. But you can create something like this.
var glb = new Object();
function newVariable(name, val){
glb.name = val;
}
You can thereafter refer to this variable using glb.name
You don't need a function for this:
Code:var name = "something";
window[name] = "abc";
alert(window.something);
Won't work as expected, you'll need to use glb[name] = val; And as toicontien pointed out, you can extend that to window[name] = val, but I wouldn't recommend either using that many global variables that you need a function to define them, or using a function to define them unless you've a very good reason.
Hi Declan,
glb[name] should be used if "glb" has to be used as an array.
Here my intention is to use glb as an object and thereafter use it's custom "attributes" of glb object as variables.
I didn't understand as to how this can give some unexpected result. Can you give an example so that I can understand this better?
Thanks,
Krishna
Example 1
Will set to the object a property called name, with the value JoeCode:function newVariable(name, val){
glb.name = val;
}
newVariable('FirstName','Joe')
While in
Example 2
Will set a property called FirstName, with the value JoeCode:function newVariable(name, val){
glb[name] = val;
}
newVariable('FirstName','Joe');
In the first example, in newVariable(name) it is an argument passed to a function, while in glb.name it is something different: a new property of the object. No relationship between the those two name there :)
No.
Kor has a great explanation there, but just to add a little to it: using the following syntax,
window["document"]["getElementById"](id)
has nothing to do with arrays, although it looks similar. Arrays are 0-index and the keys must be numeric. In that sense, there is no such thing as an associative array in JavaScript, merely numeric arrays and objects with properties.
Thanks Kor & Declan for the examples. I thought that I knew javascript. I think I'll have to start looking at the basics now
I was reading about associative arrays in javascript now. Now I completely understand what you've wrote above there Kor.
Wow.. what an explanation. Hats off to you Kor.