我有一个对象评论
。在某些情况下它可能是未定义的,而在其他情况下它看起来像
{
id: 1,
...,
next_page: 'someurl' // can also be undefined in some cases
}
我需要获取该 next_page
属性(如果存在)或在其他情况下将其设置为 null。我的代码:
let next_page = null;
if (comments && comments.next_page)
next_page = comments.next_page
它有效,但我觉得有一些更简单的方法。我说得对吗?
最佳答案
它必须为空吗?如果是这样,请选择:
const next_page = comments && comment.next_page || null
如果undefined
也很好,我建议:
const next_page = comments && comment.next_page
Javascript 的行为有点出乎意料。等号右边的表达式的结果是 undefined
如果next_page
comment
上不存在,但是comment.next_page
如果它确实存在的话。
编辑:
正如另一条评论中指出的: next_page
时要小心是一个虚假值,因为版本 #1 将返回 null
,当 comment.next_page
是 0
.
关于javascript - 获取对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49311597/