0

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.

user2898075
  • 79
  • 1
  • 3
  • 10

2 Answers2

0

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

function loadLog (id) {
    window[id] = "test";
}
joelrobichaud
  • 665
  • 4
  • 19
0

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!

briank
  • 61
  • 2