解构分配默认值
我正在学习javascript,并且在尝试在解构时为变量提供默认值时陷入了ES6语法的困境。基本上,我试图分配一个给定变量的对象的属性值,如果该值为false
/ null / undefined,我希望它是一个空对象。例如,
let foo = { prop1: 'hello!',
prop2: null
}
const prop1 = foo.prop1 || {}
const prop2 = foo.prop2 || {}
console.log(prop1) // hello!
console.log(prop2) // {}
want这就是我想要的,????是我认为与上述等效的ES6糖语法(在这里不起作用。)
let foo = { prop1: 'hello!',
prop2: null
}
const { prop1 = {} } = foo
const { prop2 = {} } = foo
console.log(prop1) // hello!
console.log(prop2) // null
但是以某种方式,有时它似乎可以在React中工作,但有时却不能..是兼容性问题吗?太混乱了!
回答:
您可能对null和undefined之间的区别感到困惑,例如:
const { dogName = 'snickers' } = { dogName: undefined }console.log(dogName) // what will it be? 'snickers'!
const { dogName = 'snickers' } = { dogName: null }
console.log(dogName) // what will it be? null!
const { dogName = 'snickers' } = { dogName: false }
console.log(dogName) // what will it be? false!
const { dogName = 'snickers' } = { dogName: 0 }
console.log(dogName) // what will it be? 0!
摘自:http :
//wesbos.com/destructuring-default-values/
以上是 解构分配默认值 的全部内容, 来源链接: utcz.com/qa/399994.html