Question

How can I set a global variable from inside a JavaScript function, using the function's parameter to name the global variable itself? For example:

function loadLog(id){
    window.id = "test";
}

So if the function was called like this...

loadLog('apple');

...then the global variable created by it would have the name "apple" with the value of "test."

I have no idea what to do and how to accomplish this. I've tried searching, but came across nothing.

Était-ce utile?

La solution

To further elaborate on elclanrs answer, when accessing the key of an object. The keys are always strings. Id is a variable not a string.

Bracket notation works such that you need to put the quotes into the bracket when accessing the key. If not, it will look for a variable with the same name. Dot notation actually converts to bracket notation, and it looks like this,

time.id --> time["id"]

Therefore you cannot use variables with dot notation because it will surround the variable in quotes.

Hope that helped!

Autres conseils

You can use square bracket notation to access the properties of an object dynamically.

function loadLog (id) {
    window[id] = "test";
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top