Sha*_*yan 3 javascript object destructuring ecmascript-6
嗨,我在这里通过函数参数Object Destructuring Demo经历了对象解构的使用示例
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = **{}**) {
console.log(size, cords, radius);
// do some chart drawing
}
// In Firefox, default values for destructuring assignments are not yet
implemented (as described below).
// The workaround is to write the parameters in the following way:
// ({size: size = 'big', cords: cords = { x: 0, y: 0 }, radius: radius =
25} = **{}**)
drawES6Chart({
cords: { x: 18, y: 30 },
radius: 30
});
Run Code Online (Sandbox Code Playgroud)
任何人都可以让我知道在函数参数末尾使用空对象赋值的原因是什么,我在上面用粗体标记(嵌入双星)?
如果你使用它,并调用没有参数的函数,它的工作原理:
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES6Chart();Run Code Online (Sandbox Code Playgroud)
如果没有,则抛出错误:
TypeError:无法将undefined转换为object
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES6Chart();Run Code Online (Sandbox Code Playgroud)
您有一个带有默认值的对象,但该对象也是一个参数,因此它需要一个空对象作为第一个参数的默认值,该对象是具有填充值的对象。
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
}
Run Code Online (Sandbox Code Playgroud)
在伪代码中,这将是:
function drawES6Chart({**first argument**} = {**default value for first argument**}) {
}
Run Code Online (Sandbox Code Playgroud)