typescript 函數(定義、參數、重載)


代碼:

// 本節內容
// 1.函數的定義
// 2.參數(可選參數/默認參數/剩余參數)
// 3.方法的重載

// js
// function add(x,y){
//     return x+y
// }
// let add1 = function(x,y){
//     return x+y
// }

// ts
// 1.函數的定義
function add(x,y):number{
    return x+y
}
// 匿名函數
let add1 = function(x,y):number{
    return x+y
}

// 2.函數的參數
function sum(x:number,y:number):number{
    return x+y
}
// 可選參數? (一般放在參數列表的末尾)
// 默認參數
function show(name:string="zhangsan",age?:number):void{
    console.log(name,age)
}
show("lisi",20)
// 剩余參數
function sum2(x1, x2, ...x:number[]):number{
    var sum = 0;
    for(var i=0;i<x.length;i++){
        sum += x[i]
    }
    return x1+x2+sum
}
let res = sum2(1,2,3,4,5,6)
console.log(res)

// 3.函數的重載
function getInfo(name:string):void;
function getInfo(age:number):void;
function getInfo(str:any):void{
    if(typeof str == "string"){
        console.log("名字:",str)
    }
    if(typeof str == "number"){
        console.log("年齡",str)
    }
}
getInfo("zhangsan")

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM