ts函数.png

= 函数的传参

  1. # 形参
  2. function fun(s:string):string{
  3. console.log(s);
  4. return s;
  5. }
  1. ## 默认参数
  2. function fun(s:string="hello world"):string{
  3. console.log(s);
  4. return s;
  5. }
  6. let x = fun("good");
  1. function func(s:any):any{
  2. return s;
  3. }
  4. //返回值是任意类型

= 函数 可选参数

ts函数可选参数.png

= 函数 默认值

ts函数默认值.png

  1. // 4. 函数 参数默认值
  2. function buyGun(gunName: string = 'M416', count: number = 1): void {
  3. console.log(`I will buy 【${gunName}】,please give me ${count} of gun`)
  4. }
  5. // 4.1 两个都是用默认值
  6. buyGun(); // buyGun('M416', 1)
  7. // 4.2 前面的传,后面的参数不传
  8. buyGun('AK47'); //buyGun('AK47', 1)
  9. // 4.3 两个都是用实参
  10. buyGun('M24', 10);
  11. // 4.4 前面的不传,后面的传
  12. buyGun(undefined, 10) // buyGun('M416', 10)

= 函数 剩余参数

ts函数剩余参数.png

  1. // 5. 函数 剩余参数
  2. function add(x: number, y: number, ...restOfNum: number[]): void {
  3. // 5.1 创建一个 求和 变量,保存 求和结果,将 x 和 y 的值 求和 后 存入
  4. let resNum: number = x + y;
  5. // 5.2 使用 for of 语法 遍历 剩余参数 数组中 每个元素,并 累加到 求和变量中
  6. for(let ele of restOfNum) {
  7. resNum += ele;
  8. }
  9. // 5.3 将 结果 打印出来
  10. console.log('Sum:' + resNum);
  11. }
  12. add(1, 2); // 3
  13. add(1, 2, 3, 4, 5, 6, 7); // 28