ES6破坏对象赋值功能参数默认值 [英] ES6 destructuring object assignment function parameter default value

查看:172
本文介绍了ES6破坏对象赋值功能参数默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过函数参数传递中的对象解构使用示例对象解析演示

  function drawES6Chart({size ='big',cords = {x :0,y:0},radius = 25} = ** {} **){
console.log(size,cords,radius);
//做一些图表绘图
}

//在Firefox中,解构分配的默认值尚未实现
(如下所述)。
//解决方法是以下列方式写入参数:
//({size:size ='big',cords:cords = {x:0,y:0},radius:半径=
25} = ** {} **)

drawES6Chart({
线:{x:18,y:30},
radius:30
});

有人可以让我知道在函数参数结尾使用空对象分配的原因是什么在上面标有粗体(嵌入双星)?

解决方案

如果你使用它,并调用没有参数的函数,它的作用是:

  function drawES6Chart({size ='big',cords = {x:0,y:0},radius = 25} = {}){console.log(size,cords,radius); //做一些图表绘图} drawES6Chart();  



抛出错误:


TypeError:无法将未定义转换为对象


  function drawES6Chart({size ='big',cords = {x:0,y:0 },radius = 25}){console.log(size,cords,radius); //做一些图表绘图} drawES6Chart();  


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆