开发者

JavaScript - select which variable to pass based on the value of another variable (without using an if)

开发者 https://www.devze.com 2023-01-27 20:35 出处:网络
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.

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

精彩评论

暂无评论...
验证码 换一张
取 消