zoukankan      html  css  js  c++  java
  • 函数

    定义函数的四种方式

    第一种,用function定义,需要明确地指出参数的类型,而函数的返回值可以通过ts的类型推断省去:

    function add1(x: number, y: number) {
      return x + y
    }
    

    第二种,通过一个变量定义函数类型

    let add2: (x: number, y: number) => number
    

    第三种,通过类型别名定义函数类型

    type add3 = (x: number, y: number) => number
    

    第四种,通过接口定义函数类型

    interface add4 {
      (x: number, y: number): number
    }
    
    PS: 
        注意:后三种只是定义函数类型,而没有具体的实现。
    

    函数参数

    在ts中形参和实参必须一一对应,多一个少一个都不行。
    可选参数(格式:参数名 + ?),即可传可不传,需要注意的是可选参数必须位于必选参数之后

    function add5(x: number, y?: number) {
      return y ? x + y : x
    }
    console.log(add5(2)) // 2
    

    为参数提供默认值

    function add6(x: number, y = 1, z: number, q = 4) {
      return x + y + z + q
    }
    console.log(add6(1, undefined, 3)) // 9
    
    PS:
        需要注意的是,在必选参数前,默认参数不可省略,必须明确传入undefined来获取默认值。
    

    以上参数的个数都是固定的,当参数不确定时,就可以使用剩余参数(格式:...参数集合: 类型)

    function add7(x: number, ...rest: number[]) {
      return x + rest.reduce((pre, cur) => pre + cur)
    }
    console.log(add7(2, 3, 2, 13, 4)) // 24
    

    函数重载

    其他语言的函数重载

    含义:如果两个函数名称相同,但是参数类型和个数不同,就实现了函数重载。
    好处:不需要为了相似功能的函数选用不同的函数名称,这样增强了函数的可读性。

    ts的函数重载要求我们先定义一系列名称相同的函数声明,然后再定义一个更宽泛的函数

    function add8(...rest: number[]): number
    function add8(...rest: string[]): string
    function add8(...rest: any[]): any {
      let first = rest[0]
      if(typeof first === 'string') {
        return rest.join('-')
      }
      if(typeof first === 'number') {
        return rest.reduce((pre, cur) => pre + cur)
      }
    }
    console.log(add8(1, 2, 3)) // 6
    console.log(add8('a', 'b', 'c')) // a-b-c
    
    PS:
        ts编译器在处理重载时,会去查询一个重载的列表,也就是我们前面定义的这个列表,并且会尝试第一个定义,如果匹配,就使用这个函数定义,如果不匹配,就接着往下查找,所以我们要把最容易匹配的函数定义写到最前面。
    
  • 相关阅读:
    Codeforces467C George and Job
    Codeforces205E Little Elephant and Furik and RubikLittle Elephant and Furik and Rubik
    Codeforce205C Little Elephant and Interval
    51nod1829 函数
    51nod1574 排列转换
    nowcoder35B 小AA的数列
    Codeforce893E Counting Arrays
    gym101612 Consonant Fencity
    CodeForces559C Gerald and Giant Chess
    CodeForces456D A Lot of Games
  • 原文地址:https://www.cnblogs.com/xfxing/p/12652382.html
Copyright © 2011-2022 走看看