Home > Mobile >  Counting up and then back down in a for loop javascript
Counting up and then back down in a for loop javascript

Time:03-18

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?

CodePudding user response:

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)
}

CodePudding user response:

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.

  • Related