Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

javascript - A function that returns the number of even numbers of an array

I need to write function that returns the number of even numbers of an array.

//======================  EXAMPLE  ========================
isEven([2,4,8,7])
3 // <======  EXPECTED OUTPUT
isEven([1,9,66,"banana"])
1 // <======  EXPECTED OUTPUT
//=========================================================

I wrote this:

function isEven(arr) {
        var count = 0;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] % 2 === 0) {
                count++;
                document.write(count);
            }
        }
    }

But to me it just returns undefined I don't know why.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One actually does never want to mix computation logic with whatever kind of output code.

In addition one could make use of Array.prototype.filter and a precise filter condition which does target odd and/or even number values ... something similar to the next provided example code ...

function getEvenCount(list) {
  return list.filter(item =>
    (typeof item === 'number') && (item % 2 === 0)
  ).length;
}
function getOddCount(list) {
  return list.filter(item =>
    (typeof item === 'number') && (item % 2 !== 0)
  ).length;
}

document.write(
  'getEvenCount([2,4,8,7]) ... ' +
  getEvenCount([2,4,8,7]) +
  '</br>'
)
document.write(
  'getEvenCount([1,9,66,"banana"]) ... ' +
  getEvenCount([1,9,66,"banana"]) +
  '</br>'
)
document.write(
  'getOddCount([2,4,8,7]) ... ' +
  getOddCount([2,4,8,7]) +
  '</br>'
)
document.write(
  'getOddCount([1,9,66,"banana"]) ... ' +
  getOddCount([1,9,66,"banana"]) +
  '</br>'
)

console.log(
  'getEvenCount([2,4,8,7]) ... ',
  getEvenCount([2,4,8,7])
);
console.log(
  'getEvenCount([1,9,66,"banana"]) ...',
  getEvenCount([1,9,66,"banana"])
);
console.log(
  'getOddCount([2,4,8,7]) ...',
  getOddCount([2,4,8,7])
);
console.log(
  'getOddCount([1,9,66,"banana"]) ...',
  getOddCount([1,9,66,"banana"])
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...