TypeScript 函数
一、常规函数定义和函数调用方式
1.常规函数定义调用
function hello() {
console.log("hello TS")
}
hello(); //hello TS
2.带返回值函数
function hello():string {
return "Hello World"
}
hello();
二、带参数函数定义和调用方式
1.带固定参数函数
function add(a: number, b: number): number {
let c:number = a+b;
return c
}
2.带可选参数和默认参数函数
function oneFun(a: string, b?: string) {
if(b) {
console.log(a + b)
} else {
console.log(a)
}
}
oneFun("hello") //hello
oneFun("hello", "TS"); //helloT
注 : \color{red}{注:} 注: 常规情况下传入参数数量要和函数定义参数相同,"?"代表该参数为可选(即传入或者不传皆可)
3.默认参数
function defaultFun(a:number,b:number = 1) {
console.log(a+b);
}
defaultFun(1) //2
defaultFun(1,2) //3
在调用函数时,如果不传入该参数的值,则使用默认参数
4.剩余参数函数
function otherFun(a: string, ...otherItem: string[]) {
console.log(a + " " + otherItem.join(" "))
}
otherFun("hello","T","S")//hello T S
当函数传入参数数量未知时,我们可以使用剩余参数来定义
三、匿名函数定义和调用方式
1.匿名函数及其自调用
//匿名函数
let noName = function(a:number,b:number) {
console.log(a+b);
};
noName(1,2); //3
// 自调用
(function() {
console.log("hello ts");
})() //hello ts
四、构造函数定义和调用方式
let creatFun = new Function("a", "b", "console.log(a+b)")
creatFun(1,2) //3
注 : \color{red}{注:} 注: let creatFun = new Function ([arg1[, arg2[, ...argN]],] funBody)
funBody是一个含有包括函数定义的 JavaScript 语句的字符串,其前面为该函数的参数列表
五、递归函数定义和调用方式
递归函数即在该函数内调用该函数,比如解决1—N的和可以通过递归解决
function myFun(a:number):number {
if (a <= 1) {
// 停止执行
return 1;
} else {
return (a + myFun(a - 1)); // 调用自身
}
}
let oneSum = myFun(100);
console.log(oneSum)//5050;
六、箭头函数定义和调用方式
1.无参数
let arrowFun = () => {
console.log("hello Ts")
}
arrowFun(); //hello Ts
2.单个参数
let arrowFunTwo = (a:number) => {
console.log(a)
}
arrowFunTwo(2); //2
当参数只有一个时也可以去掉括号
let arrowFunTwo = a => {
console.log(a)
}
arrowFunTwo(2); //2
3.多个参数
let arrowFunThree = (a:number,b:number) => {
console.log(a+b)
}
arrowFunThree(1,5); //6
六、函数重载定义和调用方式
当我们想让一个函数有多个功能时可以使用函数重载
let allStr:any[] = ["H","e","l","l","o",1];
//定义重载
function differentFun(a:string):string;
function differentFun(a:string[]):string;
//实现
function differentFun(oneArg: unknown):unknown {
if (typeof oneArg === 'string') {
return oneArg;
} else if (Array.isArray(oneArg)) {
return oneArg.join("");
}
throw new Error('false value');
}
console.log(differentFun(allStr)); //Hello1
console.log(differentFun(allStr[0])); //H
console.log(differentFun(allStr[5])); //Error: false value
有问题可以在下面评论,我会为大家解答。