代碼:
// 本節內容 // 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")
.