1.函数定义
在ts中函数有返回值,要定义返回值的类型,当函数没有返回值时,则用void来定义
//有返回值
function testMethod():string{
return 'hhhhh'
}
let testMethod:number = function(){
return 11
}
//无返回值
function testMethod():void{
····
}
let testMethod:void = function(){
····
}
2.函数参数
(1)形参实参一般用法
//在形参后端加上冒号来定义参数类型
function test(name:string,age:number,other:any):void{
}
//调用时,实参类型必须要一一对应,数量必须相等
test('张婷',18,true)
(2)可选参数(即可传可不传的参数)
在形参的后面加上问号即可
function test(name:string,age:number,other?:any):void{
}
test('zhang',1)
(3)参数默认值
带默认值的参数也是可传可不传,不传则取默认值
function test(name:string='张婷',age:number=18):void{
}
//直接调用test即可
test()
//跳过第一个参数传参,将其设置为undefined即可
test(undefined,78)
(4)剩余参数,不确定参数个数时使用
剩余参数定义:…参数名:参数数组类型[]
不确定类型时可用any
1.剩余参数只能为数组
2.一个函数只能有一个剩余参数
function test(name:string,age:number,...other:string[]):void{
for(item of other){//other中的值可通过for循环遍历出来
console.log(item)
}
}
//调用
test('name',12,'hh','mm','ss')