JavaScript Variable Variables
In PHP, variable variables allow accessing variables by a name stored in another variable. Can the same be done in JavaScript?
Answer:
No, there is no direct equivalent in JavaScript. However, there are techniques to simulate a limited functionality:
let key = "variable"; window[key] = "Hello, World!"; console.log(window.variable); // Display "Hello, World!"
const obj = { [`${variable}`]: "Hello, World!" }; console.log(obj.variable); // Display "Hello, World!"
Caution:
While these techniques offer some flexibility, they have limitations and potential security risks. It's crucial to use them judiciously or consider cleaner alternatives, such as using a Map or Symbol for variable name storage and retrieval.
Don't Use eval:
The use of eval is generally discouraged. It can introduce security vulnerabilities and lead to performance issues.
The above is the detailed content of Can JavaScript Achieve the Functionality of PHP's Variable Variables?. For more information, please follow other related articles on the PHP Chinese website!