Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present).
For example,
[true, true, true, false,
true, true, true, true ,
true, false, true, false,
true, false, false, true ,
true, true, true, true ,
false, false, true, true]
The correct answer would be 17.
Hint: Don't forget to check for bad values like null/undefined
function countSheeps(arrayOfSheep) {
let count = 0;
if (arrayOfSheep === null)
return 0;
else {
for (let el of arrayOfSheep)
if (el === true)
count++;
}
return count;
}
.filter
Boolean
을 사용하여 간결하게 나타내는 방법도 있다. 정말 자바스크립트의 메소드는 알면 알수록 끝이 없는 것 같다.🙈
function countSheeps(arr) {
return arr.filter(Boolean).length;
}