function displaysPar () in JS

0
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 the pairs it just shows 0.

    
asked by anonymous 11.04.2018 / 03:12

2 answers

0

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

var pares = [];

And within if , add the even values with push :

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

Test:

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

Create an empty list and add the even values with the push method. Then return the result of this list. It would look like this.

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

   console.log(exibePar(0,20))
    
11.04.2018 / 03:49