声明

  1. 函数声明(关键字)

    1. function test() {
    2. console.log('Hello World');
    3. }
  2. 匿名函数(赋值给一个变量) ```javascript var test = function() { console.log(‘Hello World’); }

//等价于 function test() { console.log(‘Hello World’); }

  1. Typescript语法
  2. 1. 函数声明
  3. ```typescript
  4. function demo():string {
  5. return "Hello";
  6. }
  1. 匿名函数
    1. let hello = function():number {
    2. return 0;
    3. }

    传参

    返回值

    返回值设置类型,参数也指定类型 ```typescript function add(a:number , b:number):number { return a+b; } console.log(add(1 , 1)); //2 console.log(add(‘1’ , 1)); //报错,第一个函数是定义为number

function add1(a:number , b:string):string { return a+b; } console.log(add1(1 , ‘1’)); //11

  1. <a name="4qU4k"></a>
  2. ## 无返回值
  3. 无返回值的函数定义,其返回值需要定义为void
  4. ```typescript
  5. function noreturn():void {
  6. console.log('1111');
  7. }

可选参数

一般情况下,定义函数的参数,在调用时必须传入参数的数量和定义时的参数数量一致

  1. function add1(a:number , b:string):string {
  2. return a+b;
  3. }
  4. console.log(add1(1)); //报错,由于定义时需要接收两个参数,因此必须传入两个参数

有时候,部分参数不是必选的,设置为可选参数(在参数名后面加一个问号?),函数调用时就不需要传入

  1. //可选参数
  2. function add2(a:number , b?:string):string {
  3. return '';
  4. }
  5. console.log(add2(1)); //b定义为可选参数,调用时可以不传
  6. console.log(add2(1,'a')); //也可以传参,类型必须对应上

默认参数

在函数定义时,给传入参数设置默认值,调用函数时不传参数,在函数执行中该参数取默认值

  1. //默认参数
  2. function add3(a:number , b:string='Hello'):string {
  3. return a + ' - ' + b;
  4. }
  5. console.log(add3(1)); //1 - Hello , b定义为默认参数,调用时可以不传,默认为''Hello
  6. console.log(add3(1 , 'World')); //1 - World , b定义为默认参数,传入的参数值会覆盖默认值

剩余参数

剩余参数是指接收函数调用时,所传递的多余的参数,并保存到一个数组中(类型必须对应上)

  1. function add4(a:string , ...str:string[]):void {
  2. console.log(str); //['2','3' , '4' , '5']
  3. }
  4. add4('1' , '2' , '3' , '4' , '5');
  5. //错误,因为剩余参数数组定义的是string类型,因此所有传入的剩余参数类型必须为string类型
  6. add4('1' , '2' , '3' , '4' , 5);
  7. //剩余参数当做可选参数使用
  8. function add5(...str:string[]):void {
  9. console.log(str);
  10. }
  11. add5(); //output:[] 不传,则数组为空
  12. add5(1,2); //output:[1,2]

重载

通过为同一个函数提供多个不同的返回类型来实现多种不同的逻辑,即同名方法定义不同的参数和返回值

  1. function test(a:string):string;
  2. function test(a:number):number;
  3. function test(a:any):any {
  4. if(typeof a === 'string') {
  5. console.log('传入字符串');
  6. } else if(typeof a === 'number') {
  7. console.log('传入数字');
  8. }
  9. }
  10. test(1); //传入数字
  11. test('Hello'); //传入字符串
  12. test(true); //报错,没有定义boolean类型的参数