Home > Web Front-end > JS Tutorial > How Can I Dynamically Set JavaScript Variable Names Using a String?

How Can I Dynamically Set JavaScript Variable Names Using a String?

DDD
Release: 2024-12-20 18:40:14
Original
639 people have browsed it

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
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template