在js中,像a.b.c.d.e这种嵌套的值有优雅的方法判空吗?

包括但不限于中间有一层的值是null或undefined,或者中间某层是数组,一个一个if下去感觉有点麻烦,而且字符串型要判断 ''、null、undefined

阅读 5.1k
5 个回答

有呀 可选链
const res = a?.b?.c?.d?.e
就是兼容性要求比较高
如果你是babel7以上 可以用插件支持 @babel/plugin-proposal-optional-chaining

可以自己写一个模拟点操作符的。传一个字符串进去 'a.b.c[0].d.x.xx', 然后递归一层一层判断.没出点操作符的时候好些人这么做

const isObject = (obj) => obj && typeof obj === 'object' ? true : false;

const untieObjPath = objPath =>
    objPath && objPath.trim() ? objPath.split(/\.|\[|\]\./).slice(1) : null;

const invoker = (segs, obj) =>
    segs.reduce((obj, prop) => isObject(obj) ? obj[prop] : null, obj);

const res = {
    response_body: {
        records: [
            { user: { id: 100000 } },
            null,
            { user: { id: 0 } },
            { user: 'Boooroo' },
            50000
        ]
    }
}


for (const i in [...Array(5).keys()]) {
    const objPath = `res.response_body.records[${i}].user.id`;
    const segs = untieObjPath(objPath);
    console.log(invoker(segs, res));
}

// result:
// 100000
// null
// 0
// null
// null

lodash的get可以看下

除了

const res = a?.b?.c?.d?.e;

就是

a && a.b && a.b.c && ...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题