javascript - How to access dynamic local variables -


how reference dynamic local variable? accomplished global variable:

mypet = "dog";   console.log(window["mypet"]); 

how same in local scope?


specifically i'm trying do:

myarray = [100,500,200,800];   = 1; // array index (operand 1)   b = 2; // array index (operand 2)   

depending on situation, want evaluate a<b or b<a

  • to accomplish this, set 2 variables: compare1 , compare2
  • compare1 reference either a or b , compare2 reference other
  • evaluate compare1 < compare2 or vice-versa

the following works global variables. however, want a , b local.

compare1 = "b"; compare2 = "a";   for(a=0; a<myarray.length; a++){     b = a+1;     while(b>=0 && myarray[window[compare1]] < myarray[[compare2]]){         /* something; */     b--;     } }   

if in above set compare1=a have reset compare1 every time a changed. instead, want [look at/point to] value of a.

use object instead of set of separate variables instead. (i can't think of real world situation want use dynamically named variable isn't part of group of logically related ones).

var animals = { dog: "rover", cat: "flopsy", goldfish: "killer" }; var = 'dog'; alert(animals[which]); 

Comments