Why are you denying 0
as a boolean. You are denying !0
that is equal to true
that can be converted to 1
. In javascript 1==true
. Then you get Number(1) == true
and enter as if it were a correct value but the value of numeroUsuario
is still 0
.
You need to deny the result of Number(0)== false
so that it becomes true
and show you the error message. How are you doing? You are evaluating badly.
This part of here Number(0)== false
is telling you that it is not a number. But you are converting the 0
into 1
with !
so that's where the error comes from. First you must evaluate that the data is a number, then deny it so that it enters the second part of your ifelse
.
In your code I put some alerts so you can see how the script is evaluated and understand the error that is of application of concepts. Remember that in jscript it is not necessary to define types so a 1
and 0
can represent true
and false
, so it can be modified by !
.
I also give you an alert so you can see how a number is evaluated when using this same operator (when the number is different from 1)
It is important to understand this way of working in javascript. You can make conversions between types of data without realizing it and that is what you are doing. It's kind of intricate.
This happens divided in steps (xO)
Number(!0)
becomes Number(true)
because 0=false
Number(true)
becomes Number(1)
because 1=true
Number(1)
becomes True
Do not crack your cracklings.
This is what you want to happen:
!Number(0)
is evaluated and becomes !false
!false
becomes true
;
Your cracklings are thundering.
alert( "Esto es lo que quieres !Number(0) = " + !Number("0"));
alert( "Esto es lo que estas haciendo mal Number(!0) = " + Number(!0));
alert("Esto pasa con un string '0' = " + Boolean("0"));
alert( "Por que !0= " + !0);
alert(Number(!"0") +"--"+ Number(!0));
alert("Evaluando numeros: 2 " + Boolean(2));
alert("Evaluando numeros: 9 " + Boolean(9));
alert("Evaluando numeros: !9 " + (!9) + "Aquí paso una conversión de tipo sin que te dieras cuenta. ");
let numeroUsuario, modulo;
for (var i = 0; i < 3; i++) {
numeroUsuario = prompt('Introduce un numero');
if (numeroUsuario === null) {
alert('Por favor, introduce algún valor.');
} else if(!Number(numeroUsuario) || isNaN(numeroUsuario) || numeroUsuario === '') {
alert('Por favor, introduce un valor numérico válido.');
} else {
if (numeroUsuario % 2 === 0) {
modulo = 'par';
alert('El numero ' + numeroUsuario + ' es ' + modulo);
} else {
modulo = 'impar';
alert('El numero ' + numeroUsuario + ' es ' + modulo);
}
}
}