es6中rest运算符和扩展运算符(...)

rest运算符(...args)

ES6中引入rest参数,可以获取函数的参数,用来代替arguments参数。

arguments使用

        function fn() {
            console.log(arguments);
        }
        fn(3, 21, 1)

控制台输出结果

rest运算符使用

例1:

        function fn1(...args) {
            console.log(args);
        }
        fn1(2, 31, 6)

控制台输出结果

例2:

        function fn2(a, b, ...args) {
            console.log(a);
            console.log(b)
            console.log(args)
        }
        fn2(1, 9, 1)

输出结果

arguments与rest运算符的区别:

  1. arguments返回的是对象,而rest返回的是数组类型
  2. rest参数返回的数值可以使用数组的相关方法进行处理,对值的操作更方便
  3. 使用rest参数时候,...args参数只能在最后面,否则会报错

扩展运算符(...)

...相当于 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

console.log(...[1, 2, 3, 5])
console.log(1, ...[2, 8, 4], 5)
console.log(...['hello', 'world']);

控制台显示结果

数组的扩展运算符

1.拼接数组

        const arr1 = [2, 4, 21]
        const arr2 = ['hell', '你好']
        const arr = [...arr1, ...arr2]
        console.log(arr);
     //输出结果: [2, 4, 21, "hell", "你好"]

2.拷贝数组

const arr4 = [...arr]
console.log(arr4);
//输出结果[2, 4, 21, "hell", "你好"]

3.将伪数组转化为真正的数组

        const divs = document.querySelectorAll('div')
        console.log(divs)
        const divArr = [...divs]
        console.log(divArr)

4.将字符串转化为数组

 console.log(...'helloworld');
//h e l l o w o r l d

对象的扩展运算符

对象中的扩展运算符(...)用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中

       let obj = {
            a: 1,
            b: 2
        };
        let obj1 = {...obj
        };
        console.log(obj1);  //{a: 1, b: 2}

等价于

let obj3 = Object.assign({}, obj); // { a: 1, b: 2 }

Object.assign方法用于对象的合并,将原对象中所的属性复制到目标对象。 

Object.assign方法的第一个参数是目标对象,后面的参数都是原对象。(如果目标对象与原对象有同名属性,或多个原对象有同名属性,则后面的属性会覆盖前面的属性)。

如果用户自定义的属性,放在扩展运算符后面,则扩展运算符内部的同名属性会被覆盖掉。

 let obj4 = {...obj, ...{a:2, b: 4}};  // {a: 2, b: 4}

猜你喜欢

转载自blog.csdn.net/weixin_57399180/article/details/117754659
今日推荐