Javascript number stack pairs

Asked

Viewed 7,645 times

0

I’m trying to pull the odd numbers out of a stack in an expression while javascript however I can’t, someone would have a tip to help me.

Follow the code below:

var j=0, msg="";
while (j<=10){
     if(j ==10){
       msg +=j;
       break;
     }
     if(j%2 !=0){
       msg += "";
     }
    msg += j + ", ";
    j++;
  };
console.log(msg);

The console.log() shows me odd numbers too but I only want pairs.

  • Welcome mr.Aureli, if any answer solved your problem, see in this post why accepting an answer is important https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

5 answers

3

Consider printing only the even numbers between 0 and 7. I’ve managed to understand that logic:

function passandoPelosPares() {
        for (var i = 0; i < 7; i++) {
            if ((i % 2) == 0) {
                            console.log('aqui eu tenho o valor de ' + i);
            }
        }
}

passandoPelosPares();

0

I do not understand why compare with 10, the loop already understands that 10 is included. The line msg += j + ", "; should be on probation if. Finally, break is not necessary in that case.

Follows the code:

var j = 0, msg = "";
while (j <= 10) {
    if (j % 2 === 0) {
        msg += j + ", ";
    }
    j++;
}
console.log(msg);

EDIT

Compared to the 10 to end with a .

var j = 0, msg = "";
while (j <= 10) {
    if (j % 2 === 0) {
        if (j === 10){
            msg += j + ". ";
        }else{
            msg += j + ", ";
        }
    }
    j++;
}
console.log(msg);
  • It compares with 10 not to put the last comma.

  • Ah, got it. I’ll edit the answer.

0

In principle I will correct your logic, and at the end of the reply a more streamlined script.

In your code, when j is odd enters the condition if (when it is odd) and concatenates nothing, the script proceeds to the bottom line that is concatenating all values of j.

  //se for impar
  if(j%2 !=0){
     //não concatena
     msg += "";
   }
   //sai do if e executa a linha abaixo, sendo impar ou par
   msg += j + ", ";`

So you missed putting one else in your script, so if you’re odd you enter IF and does not execute the ELSE and if it is even it does not execute the IF and executes the ELSE

if(j%2 !=0){ msg += ""; }else{ msg += j + ", "; }

See the result

var j=0, msg="";
while (j<=10){
     if(j ==10){
       msg +=j;
       break;
     }
     if(j%2 !=0){
       msg += "";
     }else{
       msg += j + ", ";
    }
    j++;
  };
console.log(msg);


The same result is obtained thus:

var j=0, msg="";
while (j<=10){
     
     //só concatena se forem números pares
     if(j%2 ==0){
        msg += j + ", ";
     }
    j++;
  };
//retira ultima virgula com ultimo espaço 
msg = msg.substr(0,(msg.length -2));
console.log(msg);

0


The problem is that concatenation is always done, because it is outside the if:

if(j%2 !=0){ //e devia ser ==0 para ser pares
    msg += ""; //devia estar a juntar aqui o numero aqui
}
msg += j + ", "; //e não aqui, que irá acontecer para todos

Then it should stay that way:

if(j%2 == 0){
    msg += j + ", ";
}

For free and in the style of Codegolf, I show another (less educational) way to do the same:

let msg = [...Array(11).keys()].filter(x => x%2==0).map(x => ""+x).join(',');

console.log(msg);

0

I hope it helps;

<script type="text/javascript">
    var j=0, pares="", impares="";
    while (j<=10){
        //Concatena os números pares
        pares   +=  (j%2 == 0 )?j+",":"";
        //Concatena os números impares
        impares += !(j%2 == 0 )?j+",":"";
        j++;
     };
     //Remove o último caracter, no caso, a virgula final
     pares = pares.substr(0,(pares.length - 1)); 
     impares = impares.substr(0,(impares.length - 1)); 

    console.log(pares);
    console.log(impares);
</script>

Browser other questions tagged

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