I have searched everywhere for a solution to this seemingly simply problem to no avail. Maybe I am using the wrong terms in my search.
The following code sets 4 numeric variables to 0 when “sel” is either “instrument”, “gnss”, “surveyor2”, or “rt4”. Notice the comparators and the first part of the variable names are the same. I have several places in my code where I make similar comparisons. The way I did it works, but it seems to be a brute force way of doing it. I did it this way because I could not figure out how to use a variable name on the left side of the equation when setting or using such variables. I hope I have described this well enough to understand what I am trying to do.
Is there a better, more efficient way to do this?
if (sel === “instrument” ) {
instrumentOptionHits = 0 ;
} else if (sel === “gnss” ) {
gnssOptionHits = 0 ;
} else if (sel === “surveyor2” ){
surveyor2OptionHits = 0 ;
} else if (sel === “rt4” ) {
rt4OptionHits = 0 ;
}
The JS switch statement would be a more efficient way to do this.
switch (sel) {
case "instrument":
instrumentOptionHits = 0;
break;
case "gnss":
gnssOptionHits = 0;
break;
case "surveyor2":
surveyor2OptionHits = 0;
break;
case "rt4":
rt4OptionHits = 0;
break;
}
Thanks for your idea, which I am sure will work. However I am trying to avoid having to maintain several such "switch"es using the same list of the 4 literals. The 4 will be growing to 8 to 10 so that solution will require me to maintain all 8 to 10 of the switches frequently. The list really needs to be driven by a single list of all 8 to 10 items.
I am thinking now that creating my own JSON object filtering on the item I am looking for might be the way to go. I have not explored the concept of using “return” but that might be another approach. Any thoughts on using either?
@jimyaccino
Perhaps you could generate it like this…
myArrayX = ["instrument", "gnss", "surveyor2", "rt4"]
myArrayY = ["instrumentOptionHits","gnssOptionHits","surveyor2OptionHits","rt4OptionHits"]
if (sel === myArrayX[0]) {
instrumentOptionHits = 0;
}
for (var i=1;i<10;i++) {
else if (sel === myArrayX[i]) {
myArrayY[i] = 0;
}
}