參考網(wǎng)址:https://www.tslang.cn/docs/handbook/functions.html 可選參數(shù)和默認(rèn)參數(shù)
- 源碼
- Functions.ts
//可選參數(shù)
// function buildName(firstName:string,lastName:string) {
// return firstName + " " + lastName;
// }
// let result1 = buildName('xiaochuan','xiaoming');//'xiaochuan xiaoming'
// let result2 = buildName('xiaochuan');//這里在編譯時(shí)直接就報(bào)錯(cuò)了 Functions.ts(5,15): error TS2554: Expected 2 arguments, but got 1.
// let result3 = buildName('xiaochuan','xiaoming','xiaohong');//這里在編譯時(shí)直接就報(bào)錯(cuò)了 Functions.ts(6,15): error TS2554: Expected 2 arguments, but got 3.
//上面的話(huà)傳遞參數(shù)的數(shù)量就必須得是 兩個(gè)
//下面是不確定幾個(gè)參數(shù)時(shí)的寫(xiě)法
//在參數(shù)名稱(chēng)的后面加一個(gè) ? 號(hào) 使這個(gè)參數(shù)變?yōu)榭蛇x項(xiàng)
// function buildName(firstName:string,lastName?:string) {
// //在這里做判斷返回想應(yīng)的返回值
// if(lastName){
// return firstName + " " + lastName;
// }else{
// return firstName;
// }
// }
// let result1 = buildName('xiaochuan','xiaoming');//'xiaochuan xiaoming'
// let result2 = buildName('xiaochuan');//這里編譯時(shí)就直接通過(guò)了
// let result3 = buildName('xiaochuan','xiaoming','xiaohong');//三個(gè)參數(shù)還是同樣的報(bào)錯(cuò)洒宝,因?yàn)槌隽藚?shù)的定義數(shù)量
//默認(rèn)參數(shù)
function buildName(firstName:string,lastName="xiaochuan"){
return firstName + " " + lastName;
}
let result1 = buildName('xiaochuan');//編譯通過(guò) 返回 'xiaochuan xiaochuan'
let result2 = buildName('xiaochuan','xiaoming');//編譯通過(guò) 返回 'xiaochuan xiaoming'
// let result3 = buildName('xiaochuan','xiaoming','xiaohong');//編譯失敗 Functions.ts(33,15): error TS2554: Expected 1-2 arguments, but got 3.
document.getElementById('pid').innerHTML = result1 + "<br/>" + result2;
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TypeScript 函數(shù)-可選和默認(rèn)參數(shù)</title>
</head>
<body>
<p id="pid"></p>
<script type="text/javascript" src="Functions.js"></script>
</body>
</html>
- 效果圖
1514821767(1).jpg