扩展运算符的使用途径
1、在解构赋值中使用
let [a,b]=[1,2]
console.log(a,b) // a=1 b=2
let [c,d]=[1,2,3,4]
console.log(c,d) // 按需解构c=1 d=2
let [e,...f]=[1,2,3,4,5,6]
console.log(e,f) //e=1 f=[ 2, 3, 4, 5, 6 ]
2、用作剩余形参,就不必使用函数内置的argument伪数组
function getMax(...item: number[]) : number{
let max=item[0]
for(let i=1;i<item.length;i++){
if(max<item[i]){
max=item[i]
}
}
return max
}
console.log(getMax(2,3,4,78,23,56)) //78
3、将数组/string/对象在语法层面上展开
let number = [5,6,7,8,9]
console.log(...number) //5 6 7 8 9
let str = 'Hello World'
console.log(...str) //H e l l o W o r l d
let wc= {
name:'晴天',
age: 18
}
console.log({...wc}) //{ name: '晴天', age: 18 }
4、用与数组/对象的复制
let array_1=[1,2,3]
let array_2=[...array_1]
console.log(array_2) //[ 1, 2, 3 ]
let wc_1= {
name:'晴天',
age: 18
}
let wc_2 = {...wc_1}
console.log(wc_2) // { name: '晴天', age: 18 }
5、将字符串转换成字符数组
let str_1='Hello'
let str_2=[...str_1]
console.log(str_2) //[ 'H', 'e', 'l', 'l', 'o' ]
6、用于数组/对象的合并
let array_3=[1,2,3]
let array_4=[4,5,6]
let array_5=[...array_3,...array_4]
console.log(array_5) //[ 1, 2, 3, 4, 5, 6 ]
let wc_3= {
name:'晴天',
age: 18
}
let wc_4= {
height :'180'
}
let wc_5={...wc_3,...wc_4}
console.log(wc_5)
7、用于函数调用中
let numbers = [5, 2, 10, -1, 9]
console.log(Math.min(...numbers)) //-1