_.compact(array)
复制代码
创建一个去除所有代表falsy值的数组。如false, null, 0, "", undefined和NaN都属于falsy值。
使用方法
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
复制代码
源码分析
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @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]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = compact;
复制代码
这个方法没有什么特别之处,主要是创建一个空数组,然后循环遍历原数组如果符合条件则加入这个创建的数组。while循环相比for循环更加精简,而且直接用++将赋值和+1操作合并,更加简练。