2數組
_.compact(array)
_.compact([0, 1, false, 2, '', 3]); // => [1, 2, 3]
源代碼:spa
/** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * compact([0, 1, false, 2, '', 3]) * // => [1, 2, 3] */ //compact方法建立一個去除了全部假值的新數組 function compact(array) { let resIndex = 0//結果數組索引 const result = []//結果數組 if (array == null) {//若是參數array爲空,返回空數組 return result } for (const value of array) {//循環array if (value) { result[resIndex++] = value//若是當前值爲真,就存入結果數組 } } return result } export default compact