function displaPar() in JS

Asked

Viewed 4,035 times

-1

function exibePar(n1,n2){
            while(n1<=n2){
                if((n1%2)==0){
                var par = n1
            }
            n1++    
        }

        }

       console.log(exibePar(0,20))

My code is not showing all pairs it only shows 0.

  • What is "bold text"?

  • mistake my sorry

  • What is the purpose of this function? Display the first even number? Assemble a list of even numbers in the range?

  • set up a list of even numbers in the range

  • The.log console will not return while values, or will?!

  • Then start by creating an empty list (array) before while! And inside, insert something into that list. You have created a variable that changes value as you go through the range.

  • I don’t know I thought I would

  • The console.log is to show the end result of an action, and not loop, I imagine.

  • Aaaah yes vlw help

  • Do the q @bfavaretto said, create an array and add the values with push. Now this (n1%2)==0 could be this n1%2==0

  • can give me an idea of how to do this if it’s no bother

  • Before function: var pares = [];... within the if: pares.push(par);

  • Thanks now I’ll get

Show 8 more comments

2 answers

2

Create an empty list and add even values with the push method. Then return the result from this list. This is how it would look.

function exibePar(n1,n2){
    var lista = []  
        while(n1<=n2){
            if(n1%2==0){
            lista.push(n1)
            }
        n1++    
        }
    return lista
    }

   console.log(exibePar(0,20))

0


Create an array before the function, so it will have global scope:

var pares = [];

And within the if, add even values with push:

var pares = [];
function exibePar(n1,n2){
    while(n1<=n2){
       if((n1%2)==0){
          pares.push(n1);
       }
       n1++    
    }
}

Testing:

var pares = [];
function exibePar(n1,n2){
   while(n1<=n2){
      if((n1%2)==0){
        pares.push(n1);
      }
      n1++    
   }
}
exibePar(0,20);
console.log(pares);

Browser other questions tagged

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