rest参数与拓展运算符

1、ES6引入rest以代替arguments对象

那么先学习一下什么是arguments:首先要明白arguments是一个数组。js在设计函数时,会用arguments来储存参数。即使在定义函数时没有定义入参,也会默认用arguments来储存实际调用时传过来的所有参数。

    function f01() {
        console.log(arguments[0]);
        console.log(arguments[1]);
        console.log(arguments[2]);
    }
    f01(12, 23, 33); //12 23 33

 

★  rest参数的写法: ...变量名,变量名就等于一个数组。在实际调用时,将多余的参数解构赋值给你定义的数组。

     function f01(a, ...b) {
        console.log(a);      //12
        console.log(b[0]);   //23
        console.log(b[1]);   //33
        console.log(b[2]);   //undefined
    }
    f01(12, 23, 33); //12 23 33

 

2、函数的length属性

函数.length,会返回该函数的参数个数。但不包括设置默认值的参数,也不包括rest参数。

    let len = (function(a) {}).length; 
    console.log(len);  // 1
    len = (function (a = 5) {}).length; // 0
    console.log(len); len =(function (a, b, c = 5) {}).length; // 2
    console.log(len); len =(function(...a) {}).length; // 0
    console.log(len); len = (function(a, ...b) {}).length ; // 1
    console.log(len);

需要注意的是,rest参数之后不能再有其他参数(即rest参数只能是最后一个参数),否则会报错。

 

 

3、拓展运算符

好比rest参数的逆运算。 function a( ...arr) { ... }     调用时:  a( ...[1,2,3]);   就相当于在调用时,把数组解构赋值,作为参数依次传进函数。

f02(666, ...[1,4,7]) //相当于  f02(666,1,4,7);

 

 

4、实际应用

a)复制数组

const a1 = [1, 2]; 
// 写法一 
const a2 = [...a1]; 
// 写法二 
const [...a3] = a1;

//注意这个a3如果不写...  那就是1(解构赋值嘛)

const [...a3, b] = a1; //写成这样就报错,rest参数必须放最后

 

b)合并数组

// 扩展运算符提供了数组合并的新写法。 
let arr1 = ['a', 'b']; 
let arr2 = ['c']; let arr3 = ['d', 'e']; 
// ES5的合并数组 
let result = arr1.concat(arr2, arr3); 
// [ 'a', 'b', 'c', 'd', 'e' ] 
// ES6的合并数组 
result = [...arr1, ...arr2, ...arr3] 
// [ 'a', 'b', 'c', 'd', 'e' ]

 

c)解构赋值与拓展运算,butLast就是一个数组

// 扩展运算符可以与解构赋值结合起来,用于生成数组。
// 扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。 
const [...butLast, last] = [1, 2, 3, 4, 5];         //报错
const [first, ...middle, last] = [1, 2, 3, 4, 5];   //报错


const [first, ...rest] = [1, 2, 3, 4, 5]; 
console.log([first, ...rest]);
console.log(rest[1]);  //3

 

d) 字符串 =》数组

    let arr = [...'hello']
    console.log(arr);    //console.log(arr);

 

e)map和set,把key塞到数组(使用.keys()方法会返回一个MapIterator对象,他不是数组。),通过[ ... map.keys()]  则可以得到真正的数组。

     MapIterator对象要通过 .next() 对象 取出元素,十分不方便。

     而通过拓展运算符转换成数组,我们就可以直接通过数组来取值。

 

    let map = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]);
    let keyMapIterator = map.keys();     // MapIterator对象
    console.log(keyMapIterator.next().value);  // 需要这样才能取出来

    let keyArray = [...map.keys()];
    console.log(keyArray);           //真正的数组,可以直接keyArray[0] 取值

    let valueArray = [...map.values()];
    console.log(valueArray); // "one", "two", "three"

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值