-1

I am writing JavaScript code that has a loop. There is statement in the loop: foo = foo +1. ; I want the code to treat foo as different variable each time the loop runs. For example:

first loop -->  env.x = env.x + 2.0 ;
second loop --> env.y = env.y+ 2.0 ;
third loop -->  env.z = env.z + 2.0 ; 

I have looked at other solutions posted like using eval() and window() functions but still can't figure how to do this.

UPDATE: To help better understand my problem I am posting a part of the code:

if (profile.xChaos.toFixed(0) > 500.) {
                               
if (profile.param1 == 2.0) { 
profile.param1 = 0.25 ;
profile.param2 += 0.25 ;
console.log('Reset. param1 =' + profile.param1 + '; param2 increment = '+profile.param2);
}
else{profile.param1 += 0.25 ;}
profile.gui.updateDisplay({verbose : false}) ;
}

I would like to implement this in such a way that the code effectively executes these lines as:

if (profile.xChaos.toFixed(0) > 500.) {
                               
if (profile.x == 2.0) { 
profile.x = 0.25 ;
profile.y += 0.25 ;
console.log('Reset. x =' + profile.x + '; y increment = '+profile.y);
}
else{profile.x += 0.25 ;}
profile.gui.updateDisplay({verbose : false}) ;
}

where x,y can be chosen from a set of variables {profile.a, profile.b, profile.c . . .}. I hope this makes it clearer. Thanks.

oodNinja
  • 3
  • 3

1 Answers1

2

Make an array of property names, then iterate over that:

const keys = ['x', 'y', 'z'];
for (const key of keys) {
  env[key] = env[key] + 2.0;
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks for the solution. However, I have a complicated piece of code inside the "for". I am looking for a solution where I can use a small variable name like var1 and var2 an then just set var1 and var2 that act as env.x or env.y or env.z as required. – oodNinja Oct 01 '20 at 01:55
  • Generally, when you have a question, you should post your *actual code*, not psuedo-code - that way you can receive useful answers. Can you post your actual code? – CertainPerformance Oct 01 '20 at 02:10
  • To be clear, post some actual code, but usually a minimal reproduction of the issue you have. – dwjohnston Oct 01 '20 at 02:53
  • I used the method given by @CertainPerformance and it worked flawlessly. Marking the problem as solved. Thank you all. – oodNinja Oct 02 '20 at 10:38