• TS学习之函数


    定义函数类型(规定函数参数及函数返回值的类型,若函数没有返回值,则返回类型为null)

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

    推断类型(ts自动识别类型(按上下文归类))

    function add(x: number, y: number) {
        return x + y
    }
    //ts会自动识别出返回类型为number

    可选参数,默认参数,剩余参数

    • 可选参数(参数名旁使用 ?实现可选参数的功能,可选参数放在必填参数之后)
    function buildName(firstName: string, lastName?: string) {
        if (lastName)
            return firstName + " " + lastName;
        else
            return firstName;
    }
    
    let result1 = buildName("Bob");  // Bob
    let result3 = buildName("Bob", "Adams");  // Bob Adams
    • 默认参数(默认参数可传值也可不传,一般默认参数在必须参数之后,但也可以定义在默认参数之前,但此时必须明确传入undefined以获取默认值)
    function buildName(firstName: string, lastName: string = "Smith") {
        return firstName + " " + lastName;
    }
    
    let result1 = buildName("Bob");  // Bob Smith
    let result3 = buildName("Bob", "Adams");  // Bob Adams
    function buildName(firstName: string = "Mr", lastName: string ) {
        return firstName + " " + lastName;
    }
    
    let result1 = buildName("Bob","Adams");  // Bob Adams
    let result2 = buildName("Bob"); //error: Expected 2 arguments, but got 1.
    let result3 = buildName(undefined,"Smith")  //Mr Smith
    • 剩余参数(当参数个数不确定时)
    function buildName(firstName: string, ...restOfName: string[]) {
      return firstName + " " + restOfName.join(" ");
    }
    
    let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
    console.log(employeeName)   //Joseph Samuel Lucas MacKinzie

    this和箭头函数(传统函数的this作用域是在函数调用时确定,但箭头函数的this作用域在创建时就已经确定)

    • 传统函数
    let myobj = {
        person:["Bob","Fred","Smith"],
        myFn:function(){
            return this.person
        }
    }
    
    let test = myobj.myFn;
    console.log(test()) //undefined
    • 箭头函数
    let myobj = {
        person: ["Bob", "Fred", "Smith"],
        myFn: function () {
            return () => {
               return this.person
            }
        }
    }
    
    let test = myobj.myFn();
    console.log(test()) //[ 'Bob', 'Fred', 'Smith' ]
  • 相关阅读:
    jsp 接收汉字参数乱码
    文件下载汉字乱码
    服务器端汉字乱码
    SpringMVC + ajax
    Java正确URL解码方式:URLDecoder.decode
    spring MVC 文件上传错误
    json
    android 带checkbox的List
    Incorrect string value: 'xE8x8Bx8FxE6x99xA8...' for column 'user_name' at row 1
    django初探-创建简单的博客系统(一)
  • 原文地址:https://www.cnblogs.com/sghy/p/7742785.html
Copyright © 2020-2023  润新知