Set global variable from within function using function parameter with JavaScript [duplicate]

StackOverflow https://stackoverflow.com/questions/21357987

سؤال

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.

هل كانت مفيدة؟

المحلول

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!

نصائح أخرى

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

function loadLog (id) {
    window[id] = "test";
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top