How many Odd and Even number are the in a array

后端 未结 3 514
抹茶落季
抹茶落季 2020-12-20 10:52

I have created an Array with some numbers. I want to find out how many even, and how many odd numbers it is in this Array. I have to print it out like this: (this is j

相关标签:
3条回答
  • 2020-12-20 11:08

    You were adding arr.length which is the array length. Instead you should simply increment the number

    var tall = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50];
    
    liste(tall);
    
    function liste(arr) {
      var sumOdd = 0;
      var sumPar = 0;
    
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] % 2 === 0) {
          sumPar++;
        } else {
          sumOdd++;
        }
      }
      
      console.log("Odd : " + sumOdd);
      console.log("Par : " + sumPar);
    }

    0 讨论(0)
  • 2020-12-20 11:09

    You could iterate with Array#reduce and count only the odds. For the rest just take the difference of the length of the array and the odds.

    var tall = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
        odd = tall.reduce(function (r, a) { return r + a % 2; }, 0),
        even = tall.length - odd;
    
    console.log('odd', odd);
    console.log('even', even);

    0 讨论(0)
  • 2020-12-20 11:23

    You always add the complete Length of the array to your variable

    Try this instead of sumPar += arr.length;:

    sumPar++;
    
    0 讨论(0)
提交回复
热议问题