I’m creating an interpreter that reads
variable1: 2
variable2: 400
variable3: 31
from a text file, and initializes the variables on runtime. using eval() and Regular Expressions
class Rules{
getSegmentArgs_string(sgmnt, scope)
{
let argarray = new Array;
let vardeclaration;
for(let i=0; i<this.rules[sgmnt].length; i++)
{
let regexp = /(\w+): ([0-9\.]+)/g;
for (const match of this.rules[sgmnt][i].matchAll(regexp)) {
vardeclaration = (scope+match[1].toString() + " = "+match[2].toString()+";");
argarray[i] = vardeclaration;
}
}
return argarray;
}
setSegment(sgmnt)
{
this.segment = sgmnt;
}
init()
{
this.defaultvars = this.getSegmentArgs_string(this.segment,"this.")
for(let i=0; i<this.defaultvars.length; i++)
{
eval(this.defaultvars[i]);
}
delete(this.rules);
delete(this.defaultvars);
delete(this.segment);
}
constructor() {
this.rules = this.dump();
}
}
let rules = new Rules;
rules.setSegment(3);
rules.init();
However, I can not understand how to access these initialized variables in a for loop that dumps each variable’s name, as well as its’ value
for (const variables in rules)
{
console.log({variales});
console.log({variables}.value);
}
I’m capable of accessing the value when doing
console.log(rules.variables1,rules.variables2,rules.variables3)
but due to the nature of the task, I need to loop through all variables without naming them in code.
>Solution :
for…in gives you the key of the object properties. You have to access the value with the key
for (const key in rules)
{
console.log(key, rules[key]);
}