I have 10 variables. q1 through q10
my script is as follows:
if (q1 == '1') { q1 = 'Yes';
} else if (q1 == '2') { q1 = 'No';
} else { q1 = 'Did Not Answer'; }
I already typed this out for all 10. I am not sure if I can insert another variable into this variable.
I'm trying to do something like this:
var ex = '1';
while (ex < 11) {
if (q[ex] == '1') { q[ex] = 'Yes'; ex++;
} else if (q[ex] == '0') { q[ex] = 'No'; ex++;
} else { q[ex] = 'Did Not Answer'; ex++ }
Basically I want to eliminate 4 lines of code x 10 variables.
[ex] is a variable inside the variable (to represent q1, determine q1 = Yes, No, or Did Not Answer, then add 1 to q[ex] which would now be q2....
I understand that the [] may not be correct, I just don't know how to explain this in a way that is understandable.
Thank you.
-
what about using switch - case statement? Map with results (array) would be the best as for me, it would be understandablevarela– varela2012年06月27日 17:48:58 +00:00Commented Jun 27, 2012 at 17:48
-
possible duplicate of Alternative to a million IF statementsFelix Kling– Felix Kling2012年06月27日 17:53:19 +00:00Commented Jun 27, 2012 at 17:53
-
3Maybe instead of 10 variables you just need one - an array.Pointy– Pointy2012年06月27日 17:53:34 +00:00Commented Jun 27, 2012 at 17:53
2 Answers 2
This wouldn't limit it down all the way but you could create a function
translate = function(v)
{
if (v === '1') {
v = 'Yes';
} else if (v === '2') {
v = 'No';
} else {
v = 'Did Not Answer';
}
return var
}
Then call translate(q1) etc for each variable. That would move it to ~16 lines rather than 40 and avoid repeating code.
You also could reform your variables as an array of variables and loop through quickly like that, but I don't know where they are all being defined and how that would work for you. EDIT: Bergi has a good example of this. If you can reform your variables like that, that is the best way to go.
5 Comments
See my answer on Alternative to a million IF statements.
The while-loop is of course a good thing, you should really use an array q instead of single variables qN. You might also use a for-loop.
If you want to eleminate the if-statements, you might use an object with indexes (in here an array, which is naturally indexed from "0" to "n-1", does the same job):
var q = ["0", "1", 1, 0, 2, ...];
for (var i=0; i<q.length; i++)
q[i] = ["No", "Yes"][q[i]] || "Did Not Answer";
// result for q:
["No", "Yes", "Yes", "No", "Did Not Answer", ...]