参考文章链接
1 . 用于函数调用
myFunction(...iterableObj);
2 . 用于数组字面量
[...iterableObj,4,5,6]
目前为止,我们都是使用Function.prototype.apply方法来将一个数组展开成多个参数:
function myFunction(x,y,z){
}
var args = [0,1,2];
myFunction.apply(null,args);
使用ES6的展开运算符可以这么写:
function myFunction(x,y,...z){
//第一个参数进x,第二个进y,剩余的进c(x,y是命名参数,...z是剩余参数<只能放在最后>)
console.log(x,y,z);//0 1 [2, 3, 4, 5]
}
var args = [0,1,2,3,4,5];
myFunction(...args);//展开数组
选择性传参
function filter(type,...items){
return items.filter(item => typeof item === type);
}
filter('boolean',true,0,false);// =>[true,false]
filter('number',false,4,'welcome',7);// =>[4,7]
还可以同时展开多个数组:
function myFunction(v,w,x,y,z){
}
var args = [0,1];
myFunction(-1,...args,2,...[3]);
let cold = ['autumn','winter'];
let warm = ['spring','summer'];
//析构数组
let otherSeasons,autumn;
[autumn,...otherSeasons] = cold;
console.log(otherSeasons);
解构赋值中展开运算符只能用在最后
var a = [1,2,3,4];
var b,c,d;
[b,...c,d] = a;
console.log(c);
let a = {
aa:'aa'};
let b = {
bb:'bb'};
let c = {
...a,...b};
console.log(c);
let d = ["dd"];
let e = ["ee"];
let f = [...d, ...e];
console.log(f);
在中间插入数组
var parts = ['shoulder','knees'];
var lyrics = ['head',...parts,'and','toes'];//['head','shoulder','knees','and','toes']
在尾部插入数组(push函数)
//ES5
var arr1 = [0,1,2];
var arr2 = [3,4,5];
//将arr2中的所有元素添加到arr1中
Array.prototype.push.apply(arr1,arr2);
//ES6
var arr1 = [0,1,2];
var arr2 = [3,4,5];
arr1.push(...arr2);// 在数组arr1后面添加arr2里的元素
arr1.unshift(...arr2) //在数组arr1前面添加arr2里的元素
Array.prototype.slice
来实现数组的拷贝,但现在我们可以通过展开运算符得到数组的副本var arr = [1,2,3];
var arr2 = [...arr]; // 等同于 arr.slice()
arr2.push(4)
这里要注意,数组里的对象仍然是引用类型的,因此实际上并不是所有内容都被“拷贝”了。
let g =[{
gg:'gg'}];
let h = {
hh:'hh'};
let i =[...g,h];
console.log(i);//[{gg:'gg'},{hh:'hh'}]
let j = ['jj'];
let k = ['kk'];
let l = [...j,k];
console.log(l);//['jj','kk']
let state = {
resultList:[],
currentPage:0,
totalRows:{
}
}
let data = {
resultList:[{
new:'new'}],
currentPage:2,
totalRows:{
row:'row'}
}
let combile = {
...state,
resultList:[
...state.resultList,
...data.resultList
],
currentPage:data.currentPage,
totalRows:data.totalRows
}
console.log(combile);
Math
对象里的相关函数,在参数个数不确定的函数里使用展开运算符let numbers = [9, 4, 7, 1];
Math.min(...numbers); // 1