使用Lodash的has-method优于Vanilla-JS的好处?

时间:2019-01-14 08:11:54

标签: javascript

在看过Lodash-documentation of the has-method中的示例之后:

var object = { 'a': { 'b': 2 } };

_.has(object, 'a.b');
// => true

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

不会...

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

相同并且没有更多的代码吗?

1 个答案:

答案 0 :(得分:4)

在普通JS中,如果objectobject.a未定义,您的代码将引发错误:

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

因此是lodash方法。

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>