js - 多层嵌套Object或Array快速判断undefined并选取
js - 多层嵌套Object或Array快速判断undefined并选取 ?.
嵌套Object连续判断并选取子对象
a.b.c.d.e.f.g. ...
应用
- 获取
g
值 - 对
g
进行操作(赋值,遍历……)
传统方式
var obj={a:'test'} console.log(obj.a&&obj.a.b&&obj.a.b.c&&obj.a.b.c.d&&obj.a.b.c.d.e&&obj.a.b.c.d.e.g) // undefined
'?.'
console.log(obj?.a?.b?.c?.d?.e?.d?.g) // undefined
对象与数组各种情况与结果
// Object?.xx console.log({a:'test'}.a) // test console.log({a:'test'}?.a) // test console.log({a:'test'}.a.b) // undefined console.log({a:'test'}.a.b.c) // Uncaught TypeError: Cannot read properties of undefined (reading 'c') console.log({a:'test'}.a.b?.c) // undefined // Object?[] 不支持 console.log({a:'test'}['a']) // test console.log({a:'test'}?['a']) // Uncaught SyntaxError: Unexpected token ')' // Array?.xx console.log([][2].a) // Uncaught TypeError: Cannot read properties of console.log([][2]?.a) // undefined // Array?[] 不支持 console.log([][2]) // undefined console.log([]?[2]) // Uncaught SyntaxError: Unexpected token ')'
notice
- ie 不支持
- 仅支持
?.xxx
, 不支持?[xxx]
Lee2
分类:
javascript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步