_的不确定行为
let a = {
b : null
}
_.get(a, 'b',''); //return null
但是
_.get (a, null, '') //return ''
null是_.get()的虚假值吗?
let a = {
b : {c:{
}
} //basically a nested object
我正在尝试做_。get(a,'bc','')。toString()
,我会遇到错误,因为_.get return return null。写这篇文章的最佳可读方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第三个参数
defaultValue
将仅用于未定义
已解决的值,而不是null
。 请参阅DOCS如果您想要
null
或未定义的
,使用:以下是使用不同机制定义默认值的不同结果:
The third argument
defaultValue
will only be returned forundefined
resolved values, notnull
. see docsIf you want a fallback value for
null
orundefined
, use the nullish coalescing operator:Below are different results using different mechanisms in defining default value:
在
您请求属性
a['b']
时,它恰好是null
,它不是undefined
,因此您得到 < code>null 作为最终结果。接下来,您请求属性
a['null']
,该属性不存在,因此它未定义
,最终得到后备值''
。最后,您似乎要求
a['b']['c']
,这将是一个空对象。然而,点线路径表示法是 Lodash 特有的。如果您使用下划线,则默认情况下该路径会被解释为a['bc']
,该路径不存在且未定义
。在这种情况下,您应该得到''
作为最终结果。即使您使用的是a = {b: null}
的原始值,我认为该表达式不可能导致null
。事实上,如果您使用 Underscore 并且想要检索
b
属性中嵌套的c
对象,则有两种选择。首先,您可以使用数组路径表示法,它可以在 Underscore 和 Lodash 之间移植:其次,您可以重写
_.toPath
为所有 Underscore 函数启用点分路径表示法:我不推荐这样做,因为它可能会破坏尝试检索名称中包含句点字符
.
的属性的代码。我提到它是为了完整性;使用你自己的判断。In
you ask for the property
a['b']
, which happens to benull
, which isn'tundefined
, so you getnull
as the final result. Next, inyou ask for the property
a['null']
, which doesn't exist, so it'sundefined
, and you end up with the fallback value''
. Finally, withyou seem to be asking for
a['b']['c']
, which would be an empty object. However, the dotted path notation is Lodash-specific. If you are using Underscore, the path is interpreted asa['b.c']
by default, which doesn't exist and isundefined
. In that case, you should get''
as the final result. I see no way this expression could result innull
, even if you are using the original value ofa = {b: null}
.If you are, in fact, using Underscore and you want to retrieve the nested
c
object within theb
property, you have two options. Firstly, you can use array path notation, which is portable between Underscore and Lodash:Secondly, you can override
_.toPath
to enable dotted path notation for all Underscore functions:I wouldn't recommend this, because it can break code that is trying to retrieve properties that contain the period character
.
in the name. I mention it for completeness; use your own judgment.