Sotiris
Sotiris

Reputation: 40066

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 question is how can I use this string to access a variable with the same name?

Upvotes: 3

Views: 5987

Answers (2)

RST
RST

Reputation: 3925

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;

}

Upvotes: -1

mplungjan
mplungjan

Reputation: 177950

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]);

Upvotes: 7

Related Questions