ES6语法扩展(剩余参数与扩展运算符、set和map、遍历器、es6新增方法)

一、剩余参数和扩展运算符

1. 剩余参数

1.1 剩余参数是什么

  • 剩余参数的作用:将传入的参数组合为一个数组,即使没有传值,也会是一个空数组
  • 语法:通过 ...参数名定义,使用时直接使用对应参数名即可
    const add = (x,y,...args) => {
   
      console.log(args) // [3,4,5,6,7]
    }
    add(1,2,3,4,5,6,7) //1对应x,2对应y,剩下的会被组合成数组(剩余参数)

1.2 剩余参数的注意事项

  • 箭头函数的参数部分即使只有一个剩余参数,也不可以省略圆括号
    // 不使用剩余参数时,当只有一个参数可以省略圆括号
    const num = x => {
   
      console.log(x)
    }
    // 当使用了剩余参数,即使只有一个剩余参数,也不可以省略圆括号
    const add = (...args) => {
   
      console.log(args)
    }
    num(1)
    add(5,2,3,4)
  • 使用剩余参数代替 arguments 获取实际参数
  • arguments 是一个类数组对象,JS在调用函数时传递的参数就会被 arguments 收集到
   const fun = function() {
    
    console.log(arguments)
   }
   fun('嘟嘟',18,'女')

在这里插入图片描述

  • 箭头函数无arguments对象,可以通过剩余参数来代替
    const fun = (...args) => {
   
      console.log(args)
    }
    fun('嘟嘟',18,'女')

在这里插入图片描述

  • 剩余参数只能放在参数列表的最后,剩余参数的后面不能再有其他参数,否则会报错,剩余参数的前面可以有其他参数

1.3 剩余参数的应用

  • 当不明确传入的实参有多少时,可以使用剩余参数接收所有的参数
    const add = (...args) => {
   
      let sum = 0
      for(let i = 0; i < args.length; i++) {
   
        sum += args[i]
      }
      return sum
    }

    console.log(add(8,2,9,10,23,87))
  • 剩余参数与解构赋值结合使用(剩余元素)
  • 剩余参数不一定要作为函数参数使用
  • 不管如何使用,都必须满足:剩余参数必须位于最后
    const [a,...args] = [1,23,13,14,15]
    console.log(args)

    const {
   x,y,...args1} = {
   x:12,y:19,z:829,i:31,j:12}
    console.log(x,y,args1)

在这里插入图片描述

2. 扩展运算符

  • 扩展运算符的作用:合并多个数组或对象
  • 有扩展运算符的变量要放最后
  • 语法:...变量名

3. 剩余参数和扩展运算符的区别

  • 扩展运算符的作用是展开,剩余参数的作用是聚合

4. 数组的扩展运算符

  • 通过扩展运算符将数组展开作为函数参数
    	function foo(a,b,c) {
   
            console.log(a)
            console.log(b)
            console.log(c)
        }
        let arr = [1,2,3]
        foo(...arr)

4.1 利用扩展运算符复制数组

        const a = [1,2]
        const b = a; // 不是复制,是引用
        const c = [...a] // 复制
        a[0] = 7
        console.log(b) // [7, 2]
        console.log(c) // [1,2]

4.2 利用扩展运算符合并数组

		const ARRAY1 = [1,2,3]
        const ARRAY2 = ['a','b']
        const ARRAY3 = ['我是数组']
        const ARRAY = [...ARRAY1,...ARRAY2,...ARRAY3]
        console.log(ARRAY) // [1,2,3,'a','b','我是数组']

4.3 利用扩展运算符将字符串转为数组

        console.log([...'你好嘟嘟']) // ['你', '好', '嘟', '嘟']

4.4 利用扩展运算符将类数组转换为数组

  • 常见类数组arguments、NodeList
function add() {
   
  console.log([...arguments]);
}
add(2,8,19,10)

5. 对象扩展运算符

  • 对象必须写在 {} 中进行展开

5.1 扩展运算符复制对象

const person = {
   
  name:'嘟嘟',
  age:19,
  sex:'女'
}
console.log({
   ...person}) // {name: '嘟嘟', age: 19, sex: '女'}

5.2 扩展运算符合并对象

  • 属性同名时,后面的属性会覆盖前面的
const person = {
   
  name:'嘟嘟',
  age:19,
  sex:'女'
}
const person1 = {
   
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值