How can I display existing even numbers up to the given number via a dialog, using a loop for
and a prompt
?
I have something like this but it doesn't work for me.
let paresalerta = prompt(`Indica hasta que número quieres ver : `);
let pares = [''];
if (paresalerta == null || paresalerta == '') {
alert('Debes introducir un valor');
}
for (let i = 0; i < pares.length; i++) {
if (i % 2 == 0) {
document.getElementById('salida').innerHTML = pares;
}
}
<div id="salida" ></div>
The value of interest is
paresalerta
And if you want to validate even the entered number you should use let i = 0; i
<=
look alert; i++I think you wanted to do something like this:
I don't know what you want to do with the pairs variable or why you evaluate it in
for
if it's just an array with a single empty string.It
for
should look like this, evaluating the pairalert variable :It can be done in the following way. First you have to calculate half of the entered number.
Using
Math.floor
makes sure the result is an integer:So, an array is created with half the input length:
The array will be displayed in the
div
withid="salida"
:It can then be iterated with
map
, using a variable outside the iteration, which we calli
. It is added by 2.Since you add to 2, if the variable
i
starts at 0, the first will be 2... For the first to be 0, the variablei
has to be -2.To convert the input from a string to a number, put a
+
on the left. Also, sincei
it is -2, we have to adjust the length, adding 2.Full code:
I see that they already answered you, I would just like to provide another way to calculate even numbers recursively:
You should also ask for two numbers: a lower bound and an upper bound so that you can visualize the numbers in a range
cotainferior <= n <= cotasuperior
.I hope it helps you. All the best.