Skip to content Skip to sidebar Skip to footer

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 var

alert(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:

function save($animal) {
    if(!$animal) return false;
    file_put_contents($animal.'.json', json_encode($$animal));
    return true;
}

In Nodejs/Javascript it could be done like this

// my variables in NodeJS/Javascript
let dogs  = [...]; //dog values
let cats  = [...]; //cat values
let sheep = [...]; //sheep values

function save(animal) {
    if (!animal) return false;

    let animalType = {};
    animalType.dogs  = dogs;
    animalType.cats  = cats;
    animalType.sheep = sheep;    

    fs.writeFile(animal + '.json', JSON.stringify(animalType[animal]), function (err){
       if (err) return false;
    });
    return true;

}

Post a Comment for "Use Variable's Value As Variable In Javascript"