2019
TL;DR
eval
operator can run string expression in the context it called and return variables from that context;
literal object
theoretically can do that by write:{[varName]}
, but it blocked by definition.
So I come across this question and everyone here just play around without bringing a real solution. but @Axel Heider has a good approaching.
The solution is eval
.
almost most forgotten operator. ( think most one is with()
)
eval
operator can dynamically run expression in the context it called. and return the result of that expression. we can use that to dynamically return a variable's value in function's context.
example:
function exmaple1(){
var a = 1, b = 2, default = 3;
var name = 'a';
return eval(name)
}
example1() // return 1
function example2(option){
var a = 1, b = 2, defaultValue = 3;
switch(option){
case 'a': name = 'a'; break;
case 'b': name = 'b'; break;
default: name = 'defaultValue';
}
return eval (name);
}
example2('a') // return 1
example2('b') // return 2
example2() // return 3
Note that I always write explicitly the expression eval
will run.
To avoid unnecessary surprises in the code. eval
is very strong
But I'm sure you know that already
BTW, if it was legal we could use literal object
to capture the variable name and value, but we can’t combine computed property names and property value shorthand, sadly, is invalid
functopn example( varName ){
var var1 = 'foo', var2 ='bar'
var capture = {[varName]}
}
example('var1') //trow 'Uncaught SyntaxError: Unexpected token }`