Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
Counting up and then back down in a for loop javascript
Function oddNumbers(){
Var odds ="";
For(index=0; index <=10; index ++){
If(index%2 !=0){odds+=index +"."}
}
}

OddNumbers();

Trying to count all odd counting numbers up then back down again in a for loop. I can get it to go up with the code again. But when I try nested for I cannot get it to go back down again in the same loop. How would I get it to loop up then back down?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Assuming you want to use only one loop definition, you have to define custom conditionExpression and incrementExpression.

Here is a quick example.

var direction = 1;

//REM: What gets added on each iteration?
function incrementExpression(){
  //REM: Increase or decrease depending on direction
    return 1*direction
}

//REM: What gets evaluated on each iteration?
function conditionExpression(i){
    if(i < 10 && direction === 1){
        return true
    }
    if(i === 10 && direction === 1){
        direction = -1
        return true
    }
    if(i >= 0 && direction === -1){
        direction = -1
        return true
    };

    //REM: Returns false if direction downwards and i lower zero
    return false
}

for(var i=0; conditionExpression(i); i+=incrementExpression(i)){
    console.log(i)
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can reverse your for loop on your use-case. See code snippet below:

function oddNumbers() {
var odds = "";
  
  for(index=0; index <=10; index ++){
    if(index%2 !=0) {
      odds+=index +"."
      console.log(odds);
    }
  }
  
  for(index = 10; index > 0; index--) {
    if(index % 2 != 0) {
    odds+=index +"."
        console.log(odds);
    }
  }
}

oddNumbers();

Im not sure if that's what you want but that's what I understand on your given code on your question.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda