function 函数名(参数列表): 返回值类型 {
函数体 ...
[return 返回值;]
}
let 函数名 = function (参数列表): 返回值类型 {
函数体 ...
[return 返回值;]
};
function text(name: string, age: number): string {
return `${name}${age}`;
}
console.log(text("林扬生", 24));
---
function text(name, age) {
return "".concat(name).concat(age);
}
console.log(text("林扬生", 24));
function text(name: string, age?: number): string {
return `${name}${age}`;
}
console.log(text("林扬生", 24));
console.log(text("林扬生"));
---
function text(name, age) {
return "".concat(name).concat(age);
}
console.log(text("林扬生", 24));//林扬生24
console.log(text("林扬生"));//林扬生undefined
function text(name: string, age: number=24): string {
return `${name}${age}`;
}
console.log(text("林扬生", 24));
console.log(text("林扬生"));
---
function text(name, age) {
if (age === void 0) { age = 24; }
return "".concat(name).concat(age);
}
console.log(text("林扬生", 24));//林扬生24
console.log(text("林扬生"));//林扬生24
参数的类型确定而参数个数不确定
function sum(...result: number[]): number {
let sum = 0;
for (let i = 0; i < result.length; i++) {
sum += result[i];
}
return sum;
}
console.log(sum(1, 2, 3, 4, 5));
---
function sum() {
var result = [];
for (var _i = 0; _i < arguments.length; _i++) {
result[_i] = arguments[_i];
}
var sum = 0;
for (var i = 0; i < result.length; i++) {
sum += result[i];
}
return sum;
}
console.log(sum(1, 2, 3, 4, 5));//15
function a() {
console.log(0);
}
const b = () => {
console.log(1);
}
a();b();