-1

Say i have self.option1ToCheck to self.option500ToCheck

Instead of having 500 if statements to check whether those variables are 'undefined' I made a for loop. However am facing an issue with it treating the variable title as a string rather than the actual variable.

My code is below - the result I'm currently get is an undefined value for all self.title.

Is this even possible to do or am i going off tangent as

for (var p=1; p<500; p++) {
      var title = 'option' + p + 'ToCheck';
      if (self.title != undefined){
            myArray.push(self.title);
      }
}
userMod2
  • 8,312
  • 13
  • 63
  • 115

1 Answers1

0

Use bracket notation for that purpose,

for (var p=1; p<500; p++) {
   var cache = self['option' + p + 'ToCheck'];
   if (cache !== undefined)
     myArray.push(cache);
}

Don't raise your eyebrows by looking at the variable definition inside for loop. It will be hoisted to its immediate lexical scope.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130