function safeGet (data, path){
if (!path) return undefined
var paths = path.split('.')
var res = data
while (paths.length) {
res = res[paths.shift()]
if (!res){
return undefined
}
}
return res
}

有时候我们需要访问一个对象较深的层次,但是如果这个对象某个属性不存在的话就会报错,例如:

var data = { a: { b: { c: 'ScriptOJ' } } }
data.a.b.c // => scriptoj
data.a.b.c.d // => 报错,代码停止执行
console.log('ScriptOJ') // => 不会被执行

  safeGet 函数,可以安全的获取无限多层次的数据,一旦数据不存在不会报错,会返回 undefined

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-27
  • 2022-12-23
  • 2022-02-25
  • 2021-09-20
  • 2022-12-23
相关资源
相似解决方案