How to avoid 'eval()'?

Having several objects (instances) of the same class, how do I go through all objects?
I made an array with all object names (property ‘.name’), but then I need the eval() command. (My program is a simulation of a railway interlocking.)

<script>

const mySignalNames = [];

class signal {
  constructor(a) {
    this.name = a;
    this.ok = true;
    mySignalNames.push(this.name);
  }
}

const C1 = new signal("C1");
const C2 = new signal("C2");

// during further process
C2.ok = false;

function resetSignals() {
    for (let sig of mySignalNames) {
		eval(sig + '.ok = true');
	}
}

// later on
resetSignals();

</script>

Ups - of course - simple solution, thanks!
so:

<script>

const mySignals = [];

class signal {
  constructor(a) {
    this.name = a;
    this.ok = true;
    mySignals.push(this);
  }
}

const C1 = new signal("C1");
const C2 = new signal("C2");

// during further process
C2.ok = false;

function resetSignals() {
    for (let sig of mySignals) {
		sig.ok = true;
	}
}

// later on
resetSignals();

</script>

Ok, didn’t know that modifying a global inside the class should be avoided.
So when I have a lot of signals, I will create the objects and fill mySignals in a loop, so I don’t have to write x times ‘mySignals.push(x)’.

Thanks a lot again - helpful! Further one, I’ll need all elements (tracks, signals, points etc) to reference, hence I adopted your second proposal.
In the following example, I need to reference i.e. Signal C2 having the property ‘fromTrack’ as a track object. I didn’t find how to find out the name of this object.
(In the console writing ‘elements.signals[‘C2’].fromTrack’ the output is ‘Track {ok: true}’, but I can’t find the name (it would be tr99).
Here my code:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.