JavaScript - select which variable to pass based on the value of another variable (without using an if)
I would like to choose which variable to pass to a funciton based on the value of another variable, without using an IF or switch statement.
For example, if var1 = yellow, than pass variable yellow. If var1 = red, then pass variable red. But without using an IF...
Actual example: I have a bunch of variables declared that match the names that I expect to be returned by the evt.target.$name call below. I want to pass the variable that corresponds to the value of event.target.$name.
var listener = function (evt) {
toPass = evt.target.$name;
myInfobubbles.addBubble("hello", toPass);
}
I'm a JavaScript n开发者_StackOverflow中文版ewbie so sorry if the answer is obvious.
The answer is to use bracket notation. It kind of depends where are your variables defined. If on window
(the kind-of default):
var listener = function (evt) {
toPass = evt.target.$name;
myInfobubbles.addBubble("hello", window[toPass]);
}
精彩评论