//可選參數 // function buildName(firstName:string,lastName:string) { // return firstName + " " + lastName; // } // let result1 = buildName('xiaochuan','xiaoming');//'xiaochuan xiaoming' // let result2 = buildName('xiaochuan');//這里在編譯時直接就報錯了 Functions.ts(5,15): error TS2554: Expected 2 arguments, but got 1. // let result3 = buildName('xiaochuan','xiaoming','xiaohong');//這里在編譯時直接就報錯了 Functions.ts(6,15): error TS2554: Expected 2 arguments, but got 3. //上面的話傳遞參數的數量就必須得是 兩個 //下面是不確定幾個參數時的寫法 //在參數名稱的后面加一個 ? 號 使這個參數變為可選項 // function buildName(firstName:string,lastName?:string) { // //在這里做判斷返回想應的返回值 // if(lastName){ // return firstName + " " + lastName; // }else{ // return firstName; // } // } // let result1 = buildName('xiaochuan','xiaoming');//'xiaochuan xiaoming' // let result2 = buildName('xiaochuan');//這里編譯時就直接通過了 // let result3 = buildName('xiaochuan','xiaoming','xiaohong');//三個參數還是同樣的報錯,因為超出了參數的定義數量 //默認參數 function buildName(firstName:string,lastName="xiaochuan"){ return firstName + " " + lastName; } let result1 = buildName('xiaochuan');//編譯通過 返回 'xiaochuan xiaochuan' let result2 = buildName('xiaochuan','xiaoming');//編譯通過 返回 '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;