我有以下对象称为this.props
:
{
children: null,
location: {
action: 'POP',
query: {
seconds: '300'
}
}
}
看了这个问题后,我写了以下代码:
let seconds = 0;
console.log(this.props);
if('seconds' in this.props) {
seconds = parseInt(this.props.location.query.seconds, 10);
}
console.log(seconds);
在控制台中,对象记录如上,但seconds
记录为 0。
我不明白我的 if 检查有什么问题,即使嵌套对象具有正确的属性,条件似乎也失败了(问题是当没有查询对象时,整个 this.props 对象是空的 - 所以我需要检查嵌套属性)。
秒不在 this.props 中;正在查询中。该in
运营商不递归的,只是第一层次:
if('seconds' in this.props.location.query) {
seconds = parseInt(this.props.location.query.seconds, 10);
}
console.log(seconds); // 300
如果要递归执行,请创建自己的函数:
let isIn = function (obj, key) {
return isObj(obj) ? (key in obj) || Object.values(obj).filter(f => isIn(f, key)).length > 0 : false;
}
whereisObj
是验证参数是否为对象的函数。你可以使用 lodash 或 equiv.,或者做类似的事情:
let isObj = t => (t !== null) && (typeof t === 'object');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句