ES6学习之路3----rest参数与扩展运算符

来源:互联网 发布:云计算产业链市场份额 编辑:程序博客网 时间:2024/05/20 13:15

什么是rest参数(…rest)

ES6引入rest参数(形式为“…变量名”),用于获取函数的多余参数。rest参数之后不能再有其他参数(即只能是最后一个参数)。

函数的rest参数

ES5写法:

function fn(){    for(var i = 0; i<arguments.length ; i++){        console.log(arguments[i]);    }}fn(1,2,3);//1,2,3

ES6写法:

function fn(...arg){    arg.forEach(current => console.log(current));}fn(1,2,3);//1,2,3

实例1:

function fn(...rest){console.log(rest);}fn(1);//[1]fn(1,2,3,4);//[1,2,3,4]fn.length;//0

实例2:

function fn(a,...rest){    console.log(a);    console.log(rest);}fn(1);//1   []fn(1,2,3,4);//1   [2,3,4]fn.length;//1

实例3:

function fn(a,b,...rest){    console.log(a);    console.log(b);    console.log(rest);}fn(1);//1 undefined  []fn(1,2,3,4);//1  2 [3,4]fn.length;//2

实例4:

function fn(a,...rest,b){    console.log(a);    console.log(b);    console.log(rest);}fn(1);fn(1,2,3,4);fn.length;//报错:Uncaught SyntaxError: Rest parameter must be last formal parameter

实例5:

function fn(...rest) { console.log(rest); console.log(arguments);}fn();//[]//[callee: (...), Symbol(Symbol.iterator): ƒ]fn(1,2);//[1,2]//[1,2,callee: (...), Symbol(Symbol.iterator): ƒ]

此处是谷歌浏览器测试的结果。ECMAScript6函数剩余参数(Rest Parameters)写到在Firefox浏览器会报错,所以在Firefox,(…rest)和arguments不能同时使用!

数组的rest参数

实例1:

let [a,...rest] = [1,2,3,4];console.log(a);//1console.log(rest);//[2,3,4]

实例2:

let [a,...rest] = [1];console.log(a);//1console.log(rest);//[]

实例3:

let [a,...rest,b] = [1,2,3,4];console.log(a);console.log(rest);console.log(b);//直接报错:Uncaught SyntaxError: Rest element must be last element

通过以上实例我们可以总结出:

  1. rest参数是一个真正的数组,它可使用Array.prototype上的所有方法;
  2. 对函数使用length属性时,不包含rest参数;
  3. rest参数只能作为最后一个参数,在它之后不能再有其他参数,否则会报错。

什么是扩展运算符(…)

扩展运算符可以看做是 rest 参数的逆运算,将一个数组转为参数序列。
实例1:

let arr = [1,2,3,4];console.log(...arr);//1 2 3 4

实例2:

let arr = [1,2,3,4];console.log(1,...arr,2);//1 1 2 3 4 2

实例3:

function add(...rest){    let sum = 0;    rest.forEach(current => sum += current);    return sum;}add(...[1,2,3,4,5,6]);//21
替代 apply 方法

实例1:

## Math.maxES5:Math.max.apply(null,[1,2,3,5,6,7,4,5]);//7ES6:Math.max(...[1,2,3,5,6,7,4,5]);//7## Array.prototype.pushES5:let arr = [1,2,3],arr0 = [6,7,8];Array.prototype.push.apply(arr,arr0);console.log(arr);//[1, 2, 3, 6, 7, 8]ES6:arr.push(...arr0);console.log(arr);//[1, 2, 3, 6, 7, 8]

字符串转为数组

实例:

let str = 'prototype';ES5:console.log(str.split(''));//["p", "r", "o", "t", "o", "t", "y", "p", "e"]ES6:console.log(...str);//p r o t o t y p econsole.log([...str]);//["p", "r", "o", "t", "o", "t", "y", "p", "e"]

任何 Iterator 接口的对象,都可以用扩展运算符转为真正的数组。

总结:

rest参数

  1. rest参数是将一个参数序列转化为数组;
  2. rest参数是一个真正的数组;
  3. rest参数可使用Array.prototype上的所有方法;
  4. 对函数使用length属性时,不包含rest参数;
  5. rest参数只能作为最后一个参数,在它之后不能再有其他参数,否则会报错;
  6. 在Firefox浏览器,rest参数和arguments不能同时使用,同时使用会报错。

扩展运算符

  1. 任何 Iterator 接口的对象,都可以用扩展运算符转为真正的数组;
  2. 扩展运算符将一个数组转为参数序列。