Reputation: 1847
I am having some trouble getting a loop to work. I am using the loop to match array values to variations of the variable test
. However, I am not sure how to properly go about this. I am making a quiz about Star Wars, and tried to refine the original code through a loop (commented out). Any help would be much appreciated for this amateur coder!
for (i=0; i<2;i++;){
test=document.myForm.elements[i].value;
if (test[i] ==answers[i]){
++corr;
}
else ++incorr;
}
/*test0=document.myForm.elements[0].value;
if (test0.toLowerCase()=="chewbacca"){
++corr;
}
else ++incorr;
test1=document.myForm.elements[1].value;
if (test1.toLowerCase()=="princess leia"){
++corr;
} else ++incorr;
test2=document.myForm.elements[2].value;
if (test2.toLowerCase()=="han solo"){
++corr;
}
else ++incorr;
test3=document.myForm.elements[3].value;
if (test3.toLowerCase()=="rey"){
++corr;
}
else ++incorr; */
location.reload();
alert("You got " + corr/(incorr+corr)*100 + " percent correct!");
}
Upvotes: 3
Views: 48
Reputation: 6002
The value extracted inside for loop is not a array but rather a simple value, so dont try to access it like a array test[i]
.
also use ===
when comparing the variables for strict comparing else you will get undesired results.
for (var i=0; i<2; i++;) {
test=document.myForm.elements[i].value;
if (test === answers[i]) {
++corr;
}
else ++incorr;
}
Note: For better performance run your script in strict mode, use strict;
, which would enforce you to declare all variables before using them. ref:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode
Upvotes: 3