ES6解构对象赋值函数参数默认值 [英] ES6 destructuring object assignment function parameter default value
本文介绍了ES6解构对象赋值函数参数默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在这里介绍对象解构在传递函数参数时使用的示例 对象解构演示
Hi I was going through examples of object destructuring use in passing function parameters here 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
});
谁能告诉我在上面用粗体(嵌入双星)标记的函数参数末尾使用空对象赋值的原因是什么?
Can anybody let me know what is reason of using empty object assignment at the end of function parameter which I have marked in bold(embedded in double stars) above?
推荐答案
如果你使用它,并且调用不带参数的函数,它的工作原理是:
If you use it, and call the function with no parameters, it works:
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES6Chart();
如果不是,则抛出错误:
if not, an error is thrown:
类型错误:无法将未定义转换为对象
TypeError: can't convert undefined to object
function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25}) {
console.log(size, cords, radius);
// do some chart drawing
}
drawES6Chart();
这篇关于ES6解构对象赋值函数参数默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文