[英]naming a variable using a loop with array
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
. 我正在使用循环将数组值与变量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!");
}
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]
. 在for循环中提取的值不是数组,而是一个简单的值,所以不要像数组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;
注意:为了获得更好的性能,请在严格模式下运行脚本, 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 参考: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.