Javascript function that takes two numbers (input) and displays in a list (Alert) with all even numbers between them

Asked

Viewed 45 times

-1

Hello, Everybody!

Can you help me with the code below?

I would like it to return a list of all even numbers entering inputs.

document.querySelector("#btnNumPar").addEventListener("click", function() {
    const inputNumUm = document.querySelector("#inputNumPar").value.trim();
    const inputDoisNum = document.querySelector("#inputNumParDois").value.trim();
    let todosPares=[];
    for (let i = 0; i <= inputDoisNum; i++) {
        if (i % 2 === 0) {
            todosPares.push();
            console.log(todosPares)
            // alert(`Os números pares entre ${inputNumUm} e ${inputDoisNum} são: ${todosPares}`);

        }
    }
})
  • You need to tell the push method what you want to insert into the array!

1 answer

0


Considering that the first number will always be larger than the second, and that you want the even numbers within the range of values received from inputs, you should leave your loop as follows:

for (let i = parseInt(inputNumUm); i <= parseInt(inputDoisNum); i++) {
        if (i % 2 === 0) {
            todosPares.push(i);
        }
    }

After that just perform the Alert:

alert(`Os números pares entre ${inputNumUm} e ${inputDoisNum} são: ${todosPares}`);
  • Gabriel, thank you so much! Just one more question. Alert is returning the array items one by one, as I could return all items at once?

  • You need to let your Alert out of the for, otherwise whenever the number is even it will run its alert

  • Thank you again, Gabriel!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.