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

176 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

rest运算符(...args)

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

arguments

arguments是一个类数组,每个函数中都有一个参数arguments(箭头函数不存在),在代码编译时会放在AO中

arguments不可以使用forEach、map等数组的高阶函数

全局作用域在浏览器中没有arguments,在node环境中有

        function foo(n1, n2, n3) {
  console.log(arguments); //{ '0': 2, '1': 1, '2': 444 }
  
  //  对arguments的操作
  // 1.获取参数的长度
  console.log(arguments.length); //3
  
  // 2.根据索引值获取某一个参数
  console.log(arguments[2]); //444
  
  // 3.获取当前arguments所在的函数,不可以使用arguments.callee()去调用函数,这个情况是递归
  console.log(arguments.callee);

  //   将arguments转成数组
  console.log("1", [...arguments]);
  
  console.log("2", Array.prototype.slice.call(arguments)); //绑定this的方法实现
  
  const newArr = Array.from(arguments);
  console.log("3", newArr);
}
foo(2, 1, 444);
箭头函数中获得函数中的其他参数使用args
const fn = (x, y, ...args) => {
  console.log(x, y, ...args);
};
fn(1, 2, 34, 4, "", 3);

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}