在 TypeScript 函数里
-
function buildName(firstName: string, lastName: string) { return firstName + " " + lastName; } let result1 = buildName("Bob"); // 错误,缺少参数 let result2 = buildName("Bob", "Adams", "Sr."); // 错误,参数太多了 let result3 = buildName("Bob", "Adams"); // 正确
如果我们定义了参数,则我们必须传入这些参数
除非将这些参数设置为可选,可选参数使用问号标识
可选参数必须跟在必需参数后面
-
function buildName(firstName: string, lastName?: string) { if (lastName) return firstName + " " + lastName; else return firstName; } let result1 = buildName("Bob"); // 正确 let result2 = buildName("Bob", "Adams", "Sr."); // 错误,参数太多了 let result3 = buildName("Bob", "Adams"); // 正确
默认参数
-
function function_name(param1[:type], param2[:type] = default_value) { return 0; }
剩余参数
- 不确定要向函数传入多少个参数,这时候我们就可以使用剩余参数来定义
- 允许我们将一个不确定数量的参数作为一个数组传入
-
function buildName(firstName: string, ...restOfName: string[]) { return firstName + " " + restOfName.join(" "); } let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
typescript
-
function addNumbers(...nums:number[]) { var i; var sum:number = 0; for(i = 0;i<nums.length;i++) { sum = sum + nums[i]; } console.log("和为:",sum) } addNumbers(1,2,3) addNumbers(10,10,10,10,10)
编译成 javascript 为
-
function addNumbers() { var nums = []; for (var _i = 0; _i < arguments.length; _i++) { nums[_i] = arguments[_i]; } var i; var sum = 0; for (i = 0; i < nums.length; i++) { sum = sum + nums[i]; } console.log("和为:", sum); } addNumbers(1, 2, 3); addNumbers(10, 10, 10, 10, 10);