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"