ES6扩展运算符
- 扩展运算符:
...
...
:它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。
let arr = ['h','e','l','l','o'];
console.log(...arr);
// h e l l o
可以遍历数组,将数组的数据一一展示出来。
当然也不只是可以遍历数组
console.log(...'hello');
// h e l l o
字符串也是可以进行遍历的操作。
把字符串转化为真正的数组
console.log([...'hello']);
// ['h', 'e', 'l', 'l', 'o']
当然也不会只有这一种操作。
用途:主要用于函数调用
-
接收参数,
与解构赋值结合,可以将传进来的多个参数封装在一个数组里面
fn(1,2,3,4,5) function fn(...arr){ console.log(arr); // ['1','2','3','4','5']; }
前面也还可以写参数接收数据
fn(1,2,3,4,5) function fn(a,...arr){ console.log(a,arr); // 1 [2','3','4','5']; }
但只限于扩展符前写参数,后面就不可以写参数了。写了会出错,数据都被扩展符给接收了,后面的参数又怎么可能还可以接收到数据呢。
Uncaught SyntaxError: Rest parameter must be last formal parameter rest参数必须在参数列表中位于最后
-
传参
fn(...[1,2,3]) function fn(a,b,c){ console.log(a,b,c) // 1 2 3 }
接收参数只限于扩展符前写参数,但是传参就没有这个限制
fn(1, ...[2,3] , 4) function fn(a,b,c,d){ console.log(a,b,c,d) // 1 2 3 4 }
如果实参和形参对不上时,没有接收到数据的形参就是
undefined
fn(1, ...[2,3]) function fn(a,b,c,d){ console.log(a,b,c,d) // 1 2 3 undefined }
如果扩展运算符后面是一个空数组,则不产生任何效果
复制数组
const a = [1, 2, 3];
const b = [...a];
b[0] = 0;
console.log(a); // [1, 2, 3]
console.log(b); // [0, 2, 3]
ES6之前复制数组是直接传的是内存地址,改动一个就会牵动全身。
const a = [1, 2, 3];
const b = a;
b[0] = 0;
console.log(a); // [0, 2, 3]
console.log(b); // [0, 2, 3]
合并数组
let arr = ['1','2']
let arr2 = ['3','4'];
arr = [...arr,...arr2]
console.log(arr); // ['1', '2', '3', '4']
不想破坏源数组,用一个新的数组接收即可
简单理解,详情请看https://es6.ruanyifeng.com/