0

So I have a variable named c[insert integer here]_bool. The list of variables are:

        c1_bool =                                           false,
        c2_bool =                                           false,
        c3_bool =                                           false,
        c4_bool =                                           false,
        c5_bool =                                           false,
        c6_bool =                                           false,
        c7_bool =                                           false,
        c8_bool =                                           false,

I want to loop through these variables, and add another variable, like:

var iC = 1;

while( iC < 9 ){
 if( c[here comes iC]_bool ){
  //insert code
 } else {}
 iC ++;
}

How do I do that?

Maarten Wolfsen
  • 1,625
  • 3
  • 19
  • 35

1 Answers1

0

While this is possible through the use of eval(), that is a hack and should not be used.

A better approach would be to set the flags as properties of an object. You can then use bracket notation to concatenate the name of the property. Try this:

var flags = {
    c1: false,
    c2: false,
    c3: false,
    c4: false,
    c5: false,
    c6: false,
    c7: false,
    c8: false
}

for (var i = 0; i <= Object.keys(flags).length; i++) {
    if (flags['c' + (i + 1)]) {
        // do something
    } else {}
}

Assuming there are no other properties in the object, you can just loop through it's keys:

for (var key in flags) {
    if (flags[key]) {
        console.log(key);
    } else {}
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339