【JavaScript】扩展运算符

ES6 扩展运算符

一、扩展运算符是什么?

💡扩展运算符是ES6新增的特殊符号, 拓展运算符 ’ … ’ 即三个点

1.运算符写法 …

  • 展开运算符: 数组 对象 实参
  • 合并运算符: 解构,形参

2.展开运算符

  • 作用 把数据集合展开(数组,对象,Set, Map …)
  • 就是把数据最外面的符号去掉

3.合并功能

  • 把多个数据合并成一个数据

二、扩展运算符作用

允许一个表达式在期望多个参数(用于函数调用)或多个元素(用于数组字面量)或多个变量(用于解构赋值)的位置扩展。

三、运用场景

1.展开数组
  let arr = [1, 2, 3, 4, 5]
// 使用运算符将数组展开
	console.log(...arr);
// 等价于
console.log(...[1, 2, 3, 4, 5]);
// 也等价于
console.log(1,2,3,4,5);
2.数组合并
 let arr = [1, 2, 3, 4, 5]
//  数组arr拼接到数组arr2
 let arr2 = [...arr, 1000, 2000]
 console.log(arr2);

打印合并后的数组
image.png

3.Math.max/Math.min
console.log(Math.max(...[100, 200, 300]));
// 等价于
console.log(Math.max(100, 200, 300));
// -------------------------------------------
console.log(Math.min(...[100, 200, 300]));
// 等价于
console.log(Math.min(100, 200, 300));
4.对象合并
    let obj = {name: 'tom'}
    let obj1 = {age: 18, ...obj} 
    console.log(obj1);
5.函数参数
   function fn(...arg) {
     console.log(arg);
   }    
   console.log(fn(100, 200, 300, 400)); 

接受两个参数,第一个参数表示[0]实参,第二个参数表示从[1] ~ [最后]

  function fn(a, ...arg) {
    console.log(a);
    console.log(...arg);
  }
  fn(100, 200, 300, 400, 500)

// …只能放到参数列表的最后 否者会报错
// 报错演示
function fn(...arg,a) {
    console.log(a);
    console.log(...arg);
  }
  fn(100, 200, 300, 400, 500)

6.字符串转数组
let str = 'Hello world'
  let arr = [...str]
  console.log(arr);

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芒果Cake

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值