js - 多层嵌套Object或Array快速判断undefined并选取

js - 多层嵌套Object或Array快速判断undefined并选取 ?.

嵌套Object连续判断并选取子对象

a.b.c.d.e.f.g. ...

应用

  1. 获取 g
  2. 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]
posted @ 2022-02-16 16:05  zc-lee  阅读(334)  评论(0编辑  收藏  举报