标签 Lodash 下的文章

记录几个Lodash在实际运用中遇到的小坑,提醒自己和看到这篇文章的所有人。
有时候一定要等BUG被别人发现了,才注意到是你没有理解开源库文档的含义……

1.你需要_.clone还是_.cloneDeep

最简单的理解方法就是看代码!

let a = {
    aaa: "Hello,",
    bbb: "My",
    ccc: "Friend!",
    array: [{a:3}, {a:5}, {a:6}, {a:8}],
    object: { b:12, c:22}
}
let b = _.clone(a)
let c = _.cloneDeep(a)
// 我们直接给a添加属性
a.kkk = 789
console.log(b)
// >>> {"aaa":"Hello,","bbb":"My","ccc":"Friend!","array":[{"a":3},{"a":5},{"a":6},{"a":8}],"object":{"b":12,"c":22}}
// 好像没啥问题
// 但是修改了a.object里面的属性之后……
a.object.a = 7
console.log(b)
// >>> {"aaa":"Hello,","bbb":"My","ccc":"Friend!","array":[{"a":3},{"a":5},{"a":6},{"a":8}],"object":{"b":12,"c":22,"a":7}}
// 看到object里面的属性a=7了么?

// 同理,改数组array的操作也……
a.array.push({a:233})
a.array[0].b = 996
console.log(b)
// >>> {"aaa":"Hello,","bbb":"My","ccc":"Friend!","array":[{"a":3,"b":996},{"a":5},{"a":6},{"a":8},{"a":233}],"object":{"b":12,"c":22,"a":7}}
// 我只想克隆一份,但为啥内层的值都变了?
// 这时候我们再看看c
console.log(c)
// >>> {"aaa":"Hello,","bbb":"My","ccc":"Friend!","array":[{"a":3},{"a":5},{"a":6},{"a":8}],"object":{"b":12,"c":22}}

为啥要用深克隆(cloneDeep)就很明显了吧?

2._.extend_.merge也有深浅的关系!

_.extend来对配置进行合并,结果……

let a = {
  aaa: 1,
  bbb: 2,
  ccc: 3,
  object: {
    ddd: 4,
    eee: 5,
    fff: 6,
    sub: {
      ggg: 7,
      hhh: 8,
      iii: 9
    }
  }
}

let b = {
  ccc: 15,
  bbb: 19,
  kkk: 13,
  object: {
    eee: 26,
    zzz: 32,
    sub: {
      ccc: 19,
      kkk: 26
    }
  }
}
console.log(_.extend({}, a, b))
// >>> {"aaa":1,"bbb":19,"ccc":15,"object":{"eee":26,"zzz":32,"sub":{"ccc":19,"kkk":26}},"kkk":13}
// object里面的ddd和fff属性都没了?

如果要保留a的默认值,又要用b等子集去覆盖,建议使用_.merge

console.log(_.merge({}, a, b))
// >>> {"aaa":1,"bbb":19,"ccc":15,"object":{"ddd":4,"eee":26,"fff":6,"sub":{"ggg":7,"hhh":8,"iii":9,"ccc":19,"kkk":26},"zzz":32},"kkk":13}
// 这样才符合我的需求