es6中引入扩展运算符…,它用于把一个数组转化为用逗号分隔的参数序列,它常用在不定参数个数时的函数调用,数组合并等情形。因为typeScript是es6的超集,所以typeScript也支持扩展运算符。
1.可变参数个数的函数调用
function push(array,...items) {
array.push(...items)
}
function add(...vals){
let sum=vals;
return sum;
}
let arr = [1,2,3,4,5,6,7];
let sum = add(...arr);
console.log(sum); //[1,2,3,4,5,6,7]
2.数组合并
let arr1=[1,2,3]
let arr2=[5,6]
let newarry=[88]
newarry=[2,...arr1,...arr2]
console.log(newarry) //[2, 1, 2, 3, 5, 6]
3.替代es5的apply方法
function f(x, y, z) {
// ...
}
var args = [0, 1, 2];
f(...args);
4.解构赋值
const [first, ...rest] = [1, 2, 3, 4, 5];
console.log(first) // 1
console.log(rest)// [2, 3, 4, 5]
4.转换字符串为数组
let show=[..."hello world"]
console.log(show) //["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]