Home >Web Front-end >JS Tutorial >How Can I Dynamically Set JavaScript Variable Names Using a String?
Convert a String to a Variable Name in JavaScript
Question:
While working on a JavaScript project, you stumbled upon a challenge: setting a variable inside a function using a string passed as an argument. You have explored various solutions but haven't found a satisfactory one. Consider the following code example:
const onlyVideo = true; function setVariable(variableName) { // Set onlyVideo to the value of variableName dynamically }
How can you accomplish this task in a flexible manner without relying on hardcoded if statements?
Answer:
One effective approach to achieve this is by utilizing the global object in JavaScript, 'window'. Here's how you can implement it:
const onlyVideo = true; function setVariable(variableName) { window[variableName] = onlyVideo; }
This code snippet assigns the value of onlyVideo to the variable specified by variableName within the global namespace. For instance, if variableName is "myVariable", the code would create a global variable named myVariable with a value of true.
This method provides a dynamic and flexible way to set variables based on a string input, allowing you to work with a variety of variables without hardcoding specific scenarios.
The above is the detailed content of How Can I Dynamically Set JavaScript Variable Names Using a String?. For more information, please follow other related articles on the PHP Chinese website!