lodash 源码解读 _.compact(array)

合并字符串成数组,并剔除 boolean 类型,undefined,null,但是没有处理 object 类型的,会将 object 合并到数组里面

_.compact([0, 1, false, 2, '', 3, undefined, 4, null, 5]); // => [1, 2, 3, 4, 5]
function compact(array) {
    let resIndex = 0
    const result = []
    if (array == null) {
      return result  //如果 array 为空 返回空数组
    }
    for (const value of array) { //这里采用 for of 是 es6 的一种新写法,区别于 for in 的是:for in 会遍历数组元素的 prototype,for of 只会遍历数组元素的值
      if (value) {
        result[resIndex++] = value
      }
    }
    return result
  }

 

posted on 2017-05-24 15:54  bbb324  阅读(120)  评论(0编辑  收藏  举报

导航