Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 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 Reply

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"])
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...