其他分享
首页 > 其他分享> > 2021-10-23

2021-10-23

作者:互联网

JavaScript中的三个点(…)

三个点的真身

JavaScript中的三个点(…)名叫扩展运算符,是在ES6中新增加的内容,它可以在函数调用/数组构造时,将数组表达式或者string在语法层面展开;还可以在构造字面量对象时将对象表达式按照key-value的方式展开

// 数组
var number = [1,2,3,4,5,6]
console.log(...number) //1 2 3 4 5 6
//对象
var man = {name:'蔡',height:180}
console.log({...man}) / {name:'蔡',height:180}

作用

  1. 复制
//数组的复制
var arr1 = ['hello']
var arr2 =[...arr1]
arr2 // ['hello']
//对象的复制
var obj1 = {name:'Steven'}
var obj2 ={...obj2}
obj2 //  {name:'Steven'}

  1. 合并
//数组的合并
var arr1 = ['hello']
var arr2 =['world']
var mergeArr = [...arr1,...arr2]
mergeArr  // ['hello','world']
// 对象分合并
var obj1 = {name:'Steven'}
var obj2 = {height:181}
var mergeObj = {...obj1,...obj2}
mergeObj // {name: "Steven", height: 181}
  1. 字符转数组用
var arr1 = [...'hello']
console.log(arr1)// ["h", "e", "l", "l", "o"]
  1. 函数传参
function f(a,b,c,d,e){ }
var args = [2,3]
f(1,...args,4,...[5]) //...args是将2,3添加进去,...[5]是将5添加进去

当我们想把数组中的元素迭代为函数参数时

function f(x,y,z){}
var args = [1,2,3]
f(...args)

日常项目示例(Angular)

interface Person {
  abnormal_service_qty:number; 
  alarm_qty:number;            
  factory_descr: string;       
  total_qty_data: number;      
  iot_abnormal_qty: string;    
  abnormal_maintain_qty:number; 
  ct_abnormal_qty:number;      
  free_qty:number;             
}
export class testComponent implements OnInit {
listOfData:Person[]=[];
constructor(private service:MonitorService) { }
ngOnInit() {
 
  }
this.service.getModeData(modeData).then((res)=>{  //以modeData为参数通过服务获取数据
       this.listOfData= res.result.outData.map((item)=>({ //处理数据,将total_qty_data相关内容添加进去,返回给新数组listOfData
      ...item,
      total_qty_data:`${item.iot_abnormal_qty+item.lost_contact_qty}`  //Es6模板字符串拼接
      }));

    })
   }

参考链接:https://segmentfault.com/a/1190000021975579

标签:10,name,...,23,number,qty,2021,arr1,var
来源: https://blog.csdn.net/weixin_45680024/article/details/120916735