什么是rest参数呢?
ES6引入rest参数(形式为“…变量名”),用于获取函数的多余参数。rest参数之后不能再有其他参数(即只能是最后一个参数)。
ES5写法
function fn() {
console.log(arguments)
}
fn("禹司凤","褚璇玑","昊辰")
结果,是一个对象而不是数组
ES6的写法
function f(a,b,...args) {
console.log(a)//1
console.log(b)//2
console.log(args)//[3,4,5,6,7,8]
}
f(1,2,3,4,5,6,7,8)
console.log(f.length)//2
要注意的是,…args只能写在最后,否则就会报错
总结一波:
- rest参数是一个真正的数组,它可使用Array.prototype上的所有方法;
- 对函数使用length属性时,不包含rest参数;
- rest参数只能作为最后一个参数,在它之后不能再有其他参数,否则会报错。
什么是扩展运算符?
扩展运算符可以看做是 rest 参数的逆运算,将一个数组转为参数序列。
let arr = [1,2,3,4,5];
console.log(1,...arr,2);//1 1 2 3 4 5 2
他可以用来替代apply的方法
ES5:
Math.max.apply(null,[1,2,3,5,6,7,4,5]);//7
ES6:
Math.max(...[1,2,3,5,6,7,4,5]);//7
ES5:
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 e
console.log([...str]);//["p", "r", "o", "t", "o", "t", "y", "p", "e"]
最后整体再总结一波
rest参数
- rest参数是将一个参数序列转化为数组;
- rest参数是一个真正的数组;
- rest参数可使用Array.prototype上的所有方法;
- 对函数使用length属性时,不包含rest参数;
- rest参数只能作为最后一个参数,在它之后不能再有其他参数,否则会报错;
- 在Firefox浏览器,rest参数和arguments不能同时使用,同时使用会报错。
扩展运算符
- 任何 Iterator 接口的对象,都可以用扩展运算符转为真正的数组;
- 扩展运算符将一个数组转为参数序列。