rest参数
- ES6 引入
rest
参数,用于获取函数的实参,用来代替arguments
- 函数的
length
属性,不包括rest
参数。 - ES2016 做了一点修改,规定只要函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显式设定为严格模式,否则会报错。
ES5的获取实参的方式
function date(){
console.log(arguments);
}
date('1','2','3'); //产生的不是数组,而是对象
//rest 参数:意义一样 但是结果不太一样
function date(...args){
console.log(args);
}
date('1','2','3'); //产生的是数组
产生的是数组就可以使用数组的一些方法------fifter
some
every
map
注意: rest
参数必须要放到参数最后
function fn(a,b,...args){
console.log(a);
console.log(b);
console.log(args);
}
fn(1,2,3,4,5,6);
ES6扩展运算符
...
扩展运算符能将数组转换为逗号分隔的参数序列
const tf = ['1','2','3'];
function chuwan(){
console.log(arguments);
}
chuwan(tf);
chuwan(...tf);
和rest区别
rest
放在函数声明的形参的位置
...
是放在函数调用的形参里边
扩展运算符的应用
- 数组的合并
const arr1 = ['1','2'];
const arr2 = ['3','4','5'];
//ES5 的做法
const arr3 = arr1.concat(arr2);
console.log(arr3);
//扩展运算符
const arr4 =[...arr1,...arr2];
console.log(arr4);
- 数组的克隆
const arr1 = ['1','2','3'];
const arr2 = [...arr1];
console.log(arr2); // 1 2 3
是一个浅拷贝
- 将伪数组转为真正的数组,换成数组就可以使用数组的那些方法
const divs = document.querySelectorAll('div');
console.log(divs);
const divArr = [...divs];
console.log(divArr);