--- tags: JavaScript, Codewar, Count of positives / sum of negatives title: Codewars - 8 kyu Count of positives / sum of negatives --- ###### tags: `Codewars` 、`JavaScript` 、`Count of positives / sum of negatives` ###### *date: 2022 / 11/ 7* # 💪 8 kyu Count of positives / sum of negatives **思考方式:** 1. 判斷傳入的陣列資料是否為空值。 2. 如果傳入的陣列資料有值的話,在使用迴圈判斷 判斷正、負數。 3. 最後計算正數出現的次數 和 負數的總和,放在陣列中並回傳。 **解法一**: 1. 先判斷傳入陣列資料是否為空,如果為空回傳空陣列。 2. 如果傳入的陣列有值的話,使用 `for of `跑迴圈計算陣列中正數的數量與負數的和, 最後並回傳陣列。 ```jsx = function countPositivesSumNegatives(input) { // 如果傳入的陣列為空就回傳 [] if (input === null || input.length < 1) return []; // 計算正數數量,與負數之和 let positives = 0; let negatives = 0; // 判斷正負數迴圈 for (const num of input) { num > 0 ? positives++ : negatives += num; }; // 回傳結果 return [positives, negatives]; }; console.log(countPositivesSumNegatives([0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]));//[8, -50] console.log(countPositivesSumNegatives([]));//[] ``` **解法二 (參考 Codewars 其他解法)**: 1. 使用`三元運算子`做條件判斷式,並回傳相對應的陣列資料。 2. 使用 `.filter()計算正數的數量`, `.reduce() 計算負數之和`。 3. 使用 `&& 邏輯運算子`的短路解析,判斷傳入的陣列是否有值,有值的話回傳 ? 後面的第一個陣列的值,反之回傳空陣列。 ```jsx= function countPositivesSumNegatives(input) { return (input && input.length) ? [ input.filter(x => x > 0).length, input.reduce((acc, cur) => cur < 0 ? acc + cur : acc, 0) ] : []; }; console.log(countPositivesSumNegatives([0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]));//[8, -50] console.log(countPositivesSumNegatives([]));//[] ```