My Javascript code loop is not working correctly

Asked

Viewed 40 times

0

function contar() {
    let inicio= document.getElementById('inicio').value
    let fim= document.getElementById('fim').value
    let passo= document.getElementById('passo').value
    let res= document.getElementById('res')
    res.innerHTML=`Resultado:<br>`

    if(inicio!=0 && fim!=0 && passo!=0){

       for(let c = inicio ; c <= fim ; c += passo) {
            
            res.innerHTML+=`${c}`

        }
    }
    else{
        alert('[ERRO] Não foi inserido os valores     corretamente, tente novamente.')
    }
}
body{
    background: rgb(2, 168, 168);
    font: normal 20pt Arial;
    width: 600px;
    margin: auto;
    margin-top: 200px;
}
header{
    color: white;
    text-align: center;
}
section{
    background: white;
    border-radius: 10px;
    padding: 15px;
    width: 500px;
    margin: auto;
    box-shadow: 6px 6px 6px 6px rgba(0, 0, 0, 0.288);
    text-align: left;
}
footer{
color: white;
    text-align: center;
    font-style: italic;
}
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exercício Repetição</title>
    <link rel="stylesheet" type="text/css" href="estilo.css">
</head>
<body >
        <header>
            <h1 id="title">Repetições</h1>
        </header>
        <section>
            <div id="inputs">
              <p>
                <label>Início:</label>
                <input type="number" id="inicio">
              </p>
                <label>Fim:</label>
                <input type="number" id="fim">
              <p>
                <label>Passo:</label>
                <input type="number" id="passo">
              </p>
                <input type="button" value="Contar" onclick="contar()">

            </div>
            <div id="res">
                
            </div>
        </section>
        <footer>
            <p>&copy; Joao</p>
        </footer>
        
    <script src="script.js"></script>   
</body>
</html>

Here:

if(inicio!=0 && fim!=0 && passo!=0){

   for(let c = inicio ; c <= fim ; c += passo) {
        
        res.innerHTML+=`${c}`

    }
}
  • 2

    Welcome. I don’t suppose you’ve heard of debugging, debug or debug code. It is possible in several browsers as well, just press F12 and learn how to use to inspect your code and see how it is behaving. Take a look around.

  • 3

    Related (generally on the importance of being explicit about type conversions): https://answall.com/questions/478394/math-random-definindo-values-m%C3%Adnimos-e-maximal-differentials-de-0/478396#478396

1 answer

3


Your problem is that you are performing mathematical operations with string. document.getElementById('..').value returns a string, however much the input is of the type "number", and this generates unexpected behaviors.

How to solve this?

  • Conversion!

Convert string to number types by simply adding one + in front of the variable.

See how:

let inicio = document.getElementById('inicio').value;
let fim = document.getElementById('fim').value;
let passo = document.getElementById('passo').value;
let res = document.getElementById('res');

// convertemos aqui o "fim", "passo" e "inicio" para número
fim = +fim;
passo = +passo;
inicio = +inicio;

See how the function would look contar:

function contar() {
  let inicio = document.getElementById('inicio').value;
  let fim = document.getElementById('fim').value;
  let passo = document.getElementById('passo').value;
  let res = document.getElementById('res');

  fim = +fim;
  passo = +passo;
  inicio = +inicio;

  res.innerHTML = `Resultado:<br>`;

  if (inicio != 0 && fim != 0 && passo != 0) {
    for (let c = inicio; c <= fim; c += passo) {
      res.innerHTML += ` - ${c}`;
    }
  } else {
    alert(
      '[ERRO] Não foi inserido os valores corretamente, tente novamente.',
    );
  }
}

The working code:

function contar() {
  let inicio = document.getElementById('inicio').value;
  let fim = document.getElementById('fim').value;
  let passo = document.getElementById('passo').value;
  let res = document.getElementById('res');

  fim = +fim;
  passo = +passo;
  inicio = +inicio;

  res.innerHTML = `Resultado:<br>`;

  if (inicio != 0 && fim != 0 && passo != 0) {
    for (let c = inicio; c <= fim; c += passo) {
      res.innerHTML += ` - ${c}`;
    }
  } else {
    alert(
      '[ERRO] Não foi inserido os valores corretamente, tente novamente.',
    );
  }
}
body {
  background: rgb(2, 168, 168);
  font: normal 20pt Arial;
  width: 600px;
  margin: auto;
  margin-top: 200px;
}
header {
  color: white;
  text-align: center;
}
section {
  background: white;
  border-radius: 10px;
  padding: 15px;
  width: 500px;
  margin: auto;
  box-shadow: 6px 6px 6px 6px rgba(0, 0, 0, 0.288);
  text-align: left;
}
footer {
  color: white;
  text-align: center;
  font-style: italic;
}
<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Exercício Repetição</title>
    <link rel="stylesheet" type="text/css" href="estilo.css" />
  </head>
  <body>
    <header>
      <h1 id="title">Repetições</h1>
    </header>
    <section>
      <div id="inputs">
        <p>
          <label>Início:</label>
          <input type="number" id="inicio" />
        </p>
        <label>Fim:</label>
        <input type="number" id="fim" />
        <p>
          <label>Passo:</label>
          <input type="number" id="passo" />
        </p>
        <input type="button" value="Contar" onclick="contar()" />
      </div>
      <div id="res"></div>
    </section>
    <footer>
      <p>&copy; Joao</p>
    </footer>
  </body>
</html>

I added a - in res.innerHTML += ' - ${c}'; only for easy viewing...

using Typescript, we would avoid these problems ...

Browser other questions tagged

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