[英]for loop parameter not working properly in JavaScript
Hello: I'm new programming.你好:我是新编程。 My problem is that the evaluation in the for
sentence is not working properly.我的问题是for
语句中的评估工作不正常。
With: salir='n' it works correctly使用:salir='n' 它可以正常工作
With: salir=='n' don't works.使用:salir=='n' 不起作用。
Thanks谢谢
<script type="text/javascript">
var tabla="";
var numusuario=0;
var min=0;
var max=9;
var salir='s';
numusuario=prompt("Escribe un número entre 0 y 9: ");
for(var j=1;salir='n';j++)
{
if(numusuario<0 || numusuario>=10)
{
salir='s';
numusuario=prompt("Escribe un número entre 0 y 9: ");
}
else
{
for(var x=min;x<=max;x++)
{
tabla = tabla + x + " x " + numusuario + " = " + (x*numusuario) + "\n";
}
alert(tabla);
break;
}
}
</script>
salir='n'
means assignments. salir='n'
表示赋值。 it is always return true
它总是返回true
salir=='n'
means comparision. salir=='n'
表示比较。 it is return false
because salir='s'
so s
is not equal to n
它返回false
因为salir='s'
所以s
不等于n
Several things happenning here, but main is that you are mixing different forms of flow control:这里发生了几件事,但主要是你混合了不同形式的流量控制:
salir
(exit, for non-spanish speakers) as a loop end indicator, but...您正在使用salir
(退出,对于非西班牙语扬声器)作为循环结束指示符,但是...salir='n'
evaluates to 'n'
, which is true)循环条件始终为真(因为salir='n'
评估为'n'
,这是真的)j
, with no use (you do nothing with it, it doesn't participate in the loop condition neither)您还使用了一个变量j
,但没有用(您不使用它,它也不参与循环条件)break
sentence, which exists the loop.退出循环的唯一可能性是存在循环的break
语句。As the expected behaviour is not clear to me, I cannot assume a solution, but if it is to keep running until the user writes a valid number, then write the multiplication table of that number, it could be:由于我不清楚预期的行为,我无法假设解决方案,但是如果要一直运行直到用户写入有效数字,然后写入该数字的乘法表,它可能是:
<script type="text/javascript">
var tabla="";
var numusuario=0;
var min=0;
var max=9;
var salir = 'n';
do {
numusuario=prompt("Escribe un número entre 0 y 9: ");
if(numusuario>0 && numusuario<10) {
for(var x=min;x<=max;x++)
{
tabla = tabla + x + " x " + numusuario + " = " + (x*numusuario) + "\n";
}
alert(tabla);
salir = 's';
}
} while(salir == 'n')
</script>
The do {} while ()
executes at least once and checks the condition at the end, that seems better suited in this case, we drop the j
variable and use the salir
variable as flow control until the user writes the correct number. do {} while ()
至少执行一次并在最后检查条件,这似乎更适合这种情况,我们删除j
变量并使用salir
变量作为流量控制,直到用户写入正确的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.