Home >Web Front-end >JS Tutorial >How Can I Dynamically Set JavaScript Variables Using Strings as Names?
While searching for solutions to dynamically set variables using strings as variable names, many users encounter challenges. For instance, if you have a variable named onlyVideo and you want to set the value of onlyVideo within a function, the following question arises:
"How can I dynamically assign a new value to the variable onlyVideo inside a function based on a passed string, rather than using hard-coded if statements?"
The text suggests that a better approach might exist, such as using JavaScript objects, but for beginners, a simpler method is explained. This method involves using the window object to set global variables:
window["onlyVideo"] = "new_value"; // Sets the global variable `onlyVideo`
In this specific case, window["onlyVideo"] allows you to set the onlyVideo variable's value dynamically within a function.
The above is the detailed content of How Can I Dynamically Set JavaScript Variables Using Strings as Names?. For more information, please follow other related articles on the PHP Chinese website!