I have some variables
var a = true;
var b = false;
var c = true;
and an array
var array = ['a', 'b', 'c'];
How is it possible to evaluate the elements to their corresponding truth value?
I know I can use eval(), but since it is considered harmful, are there any other options?
In some cases I will rather have the 'truth' assignment as
var truth = {'a': true, 'b': false, 'c': true};
and it seems, eval() doesn't take another option (e.g. eval('a+b', {a: 1, b: 3}) = 4)
3 Answers 3
While this doesn't answer your question, it should do what you need to do.
Rather than making those variables, you can make them properties of a local object -- then use them.
var obj = {
a: true,
b: false,
c: true
};
var array = ['a', 'b', 'c'];
array.forEach(function(val) {
console.log("Value ", val, "is ", obj[val]);
});
Because of how things are named, you could also access
obj.a = false;
or
obj["b"] = true;
1 Comment
Javascript unfortunately only provides eval that works with scopes that are out of the control of the programmer (in Python instead you can provide what should be the global and the local environment).
To achieve what you want to do the solution is implementing your own language. It may seem a huge thing but indeed it may be doable and even reasonable depending on what you need it for.
If that is needed just for configuration normally the solution in the Javascript world is to use a single JSON object, giving up with the possibility of having small helper functions or conditionals in the configuration itself.
Comments
If your variables are global, you can use window or this (when this points to the window object).
var a = true;
var b = false;
var c = true;
var array = ['a', 'b', 'c'];
for(var i = 0; i < array.length; i++){
console.log(this[array[i]]);
}
1 Comment
window object.
window['a'] == trueifais a global variable?add(({a, b}) => a+b)({a: 1, b: 3}).evalis a tool, just one generally used for evil. It can be used fine and properly if used carefully and sparingly. I'd never ship any library code with it, but I'd also probably never run into whatever craziness you appear to try to be doing. : ) Really, your problem most likely lies in how you're trying to attack it in the first place, not in some magical need for an eval-like construct.