Use Variable's Value As Variable In Javascript
I have a variable with a value, let's say var myVarMAX = 5; In HTML I have an element with id='myVar'. I combine the id with the string MAX (creating a string myVarMAX). My quest
Solution 1:
You COULD use eval, but if you have the var in the window scope, this is better
var myVarMAX = 5;
var id="MAX"; // likely not in a varalert(window["myVar"+id]); // alerts 5
However Don't pollute the global scope!
A better solution is something like what is suggested in the link I posted
var myVars = {
"myVarMin":1,
"myVarMax":5,
"otherVarXX":"fred"
} // notice no comma after the last var
then you have
alert(myVars["myVar"+id]);
Solution 2:
Since this post is referred to often, I would like to add a use case.
It is probably often a PHP programmer who gives Javascript/Nodejs a try, who runs into this problem.
// my variables in PHP
$dogs = [...]; //dog values
$cats = [...]; //cat values
$sheep = [...]; //sheep values
Let's say I want to save them each in their own file (dogs.json, cats.json, sheep.json), not all at the same time, without creating functions like savedogs, savecats, savesheep. An example command would be save('dogs')
In PHP it works like this:
functionsave($animal) {
if(!$animal) returnfalse;
file_put_contents($animal.'.json', json_encode($$animal));
returntrue;
}
In Nodejs/Javascript it could be done like this
// my variables in NodeJS/Javascriptlet dogs = [...]; //dog valueslet cats = [...]; //cat valueslet sheep = [...]; //sheep valuesfunctionsave(animal) {
if (!animal) returnfalse;
let animalType = {};
animalType.dogs = dogs;
animalType.cats = cats;
animalType.sheep = sheep;
fs.writeFile(animal + '.json', JSON.stringify(animalType[animal]), function (err){
if (err) returnfalse;
});
returntrue;
}
Post a Comment for "Use Variable's Value As Variable In Javascript"