-2

I have created the following:

var some_string = 'cb';

var a = 1;
var b = 2;
var c = 4;
var d = 8;

var mask = 0;

I want to store the a+b+c+d vars in the mask which works when I do:

mask |= c; // mask now equals 4

The problem I have is that I need to add the var value from within a loop:

mask |= some_string[0]

This doesn't work. I assume I have to convert some_string[0] because some_string[0]!=var c

EDIT: using eval works...

mask |= eval(some_string[0])

...considering eval gets such a bad rap, is there another way?

  • It's a bit confusing (pun intended). What do you expect as an output ? – axelduch Jun 26 '14 at 17:19
  • 4
    possible duplicate of ["Variable" Variables in Javascript?](http://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – CBroe Jun 26 '14 at 17:19
  • 1
    @CBroe I don't understand... what does make it a duplicate of this question ? – axelduch Jun 26 '14 at 17:21
  • Are you saying that you want to loop through the characters in the string `'cb'`, adding the values of `var c` and `var b` to your mask? This smells like an [XY problem](http://meta.stackexchange.com/a/66378/254929). – Air Jun 26 '14 at 17:21
  • @CBroe I think I got it now, and yes, now I agree that it looks like a duplicate. – axelduch Jun 26 '14 at 17:23
  • Not relevant to the problem, but why is `d` set to `5` instead of `8`? – cookie monster Jun 26 '14 at 17:24

1 Answers1

1

Can you try using an object instead of individual vars?

var some_string = 'cb';
var obj = {
    a: 1,
    b: 2,
    c: 4,
    d: 5
};

var mask = 0;

mask |= obj[some_string[0]];

alert (mask);

http://jsfiddle.net/W26Lx/

Ken Dickinson
  • 405
  • 3
  • 7