0

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 newbie so sorry if the answer is obvious.

Will Gill
  • 577
  • 2
  • 10
  • 21

1 Answers1

1

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]);
}
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
  • Hi, the variables are defined with global scope in the same area. All the JS is currently sitting in the area of my html document. Does "window" above refer to the scope of the variables? – Will Gill Nov 30 '10 at 06:00