Rest and Spread 操作符(...)
- 用来声明可以传递任意数量参数的方法
//TypeScript
function fun1(...arg) {
arg.forEach(function (arg) {
console.log(arg);
})
}
//调用函数传入不同数量的参数
fun1(1, 2, 4);
fun1(1, 5, 6, 7, 8, 4, 6);
//编译的JavaScript代码,下面出现了一箩筐
function fun1() {
var arg = [];
for (var _i = 0; _i < arguments.length; _i++) {
arg[_i] = arguments[_i];
}
arg.forEach(function (arg) {
console.log(arg);
});
}
fun1(1, 2, 4);
fun1(1, 5, 6, 7, 8, 4, 6);
//console.log
(unknown) 1
(unknown) 2
(unknown) 4
(unknown) 1
(unknown) 5
(unknown) 6
(unknown) 7
(unknown) 8
(unknown) 4
(unknown) 6
- 把任意长度的数组当做参数传递给固定数量参数的方法
function fun1(a, b, c) {
console.log(a);
console.log(b);
console.log(c);
}
var arg1 = [1, 2, 3];
var arg2 = [1, 2];
var arg3 = [1, 2, 3, 4, 5];
fun1(arg1);
fun1(arg2);
fun1(arg3);
//好,结果你猜
//可能TypeScript现在用的版本不支持。。。