代码之家  ›  专栏  ›  技术社区  ›  cluster1

与香草JS相比,使用洛达什HAS方法的好处是什么?

  •  4
  • cluster1  · 技术社区  · 6 年前

    在从 Lodash-documentation of the has-method :

    var object = { 'a': { 'b': 2 } };
    
    _.has(object, 'a.b');
    // => true
    

    我问自己: 使用这种方法的实际目的是什么?

    不会…

    if (object.a.b) {
        ...
    }
    

    相同,不是更多的代码吗?

    1 回复  |  直到 6 年前
        1
  •  5
  •   CertainPerformance    6 年前

    在普通JS中,如果 object object.a 未定义:

    const object = {};
    if (object.a.b) {
    }

    因此,罗达什法。

    console.log(_.has({}, 'a.b'));
    console.log(_.has(undefined, 'a.b'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>