扩展运算符[Rest 参数/...]
获取函数的多余参数,这样就不需要使用 arguments 对象了。rest 参数(…)搭配的变 量是一个数组,该变量将多余的参数放入数组中。
例子:
// 当传入的参数不确定或者多个的时候,就可以当做arguments来使用
function show(...a){
console.log(a); // [5, 56, 23, 100, 34]
}
show(5,56,23,100,34);
将一个数组转为用逗号分隔的参数序列
console.log(...[1, 2, 3]) // 1 2 3
console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5
克隆数组
const a1 = [1, 2];
const [...a2] = a1;
合并数组
const arr1 = ['a', 'b'];
const arr2 = ['c'];
const arr3 = ['d', 'e'];
console.log([...arr1, ...arr2, ...arr3]) // [ 'a', 'b', 'c', 'd', 'e' ]
替代 arguments
Function demo(…a){
return a
}
Demo(1,2,3,4,5)
此外扩展运算符还可以解决数组的引用的问题:
let x = [5,56,23,100,34];
let y = x;
x.push(40);
console.log(x); // [5, 56, 23, 100, 34, 40]
console.log(y); // [5, 56, 23, 100, 34, 40]
上面这个例子说明了y是x的一个引用,也就是说二者所在的内存是同一个,要想改变x不影响y的话,就要开辟一个新内存,解决方式:
let x = [5,56,23,100,34];
let y = [...x];
x.push(40);
console.log(x); // [5, 56, 23, 100, 34, 40]
console.log(y); // [5, 56, 23, 100, 34]
扩展运算符还可以用来数组的排序,此排序并不是大小排序,而是按照每一位的首位数字进行排序的,第一位相同就看第二位,依次排列,和字典式排序相似
扩展运算符
function orderBy(...x){
return x.sort();
}
console.log(orderBy(55,12,7,4,31)); // [12, 31, 4, 5, 7]
let arr = ['aaa','bbb','ccc'];
let arr2 = "aabbcc";
console.log(arr); // ["aaa", "bbb", "ccc"]
console.log(arr2); // aabbcc
console.log(...arr); // aaa bbb ccc
console.log(...arr2); // a a b b c c
综上所述,...可以完成字符串和数组之间的转换
Rest运算符
function show(a,...b){
console.log(a); // 5
console.log(b); // [56, 23, 100, 34]
}
show(5, 56, 23, 100, 34);
就是说前面的参数一一对应,后面的那个...b就代表剩下的参数,因为是剩余参数所以这个剩余运算符要放在最后的位置,因此有的人又称为剩余运算符