TypeScript入門(二)函數新特性


一、TypeScript-Rest and Spread操作符

 用來聲明任意數量的方法參數

 ...args中的...就是Rest and Spread操作符。

例1:

聲明一個可以傳任意數量的參數進來的方法

function func(...args:Array<number>) {
    args.forEach((arg) => {
        console.log(arg)
    })
}

func(1,2,3)
func(1,2,3,4)

例2: 反過來的用法

把任意長度的數組轉化成固定數量的參數調用 【ts會報錯不支持,但是編譯出來的js可以正常運行】

function func1(a,b,c) {
    console.log(a);
    console.log(b);
    console.log(c);
}

var args = [1, 2];

func1(...args); //1 2 undefined
var args2 = [7, 8, 9, 10, 11]; //7,8,9
func1(...args2);

二、TypeScript-Generator函數

babel在線編輯器

控制函數的執行過程,手動暫停和恢復代碼執行。 

es6關鍵字yeild可以讓代碼執行一半停下來。

generator函數聲明:function* 【很簡單,在function后面加個*就聲明了】

例1:簡單的例子

通過yield控制generator函數的暫停和執行。

function* doSomething(){
  console.log("start");
  yield;
  
  console.log("finish");
}

//doSomething();//這樣調用generator函數不起作用 ,必須聲明為一個變量
var fun1=doSomething();
fun1.next();
fun1.next();

 

調用一次next(),走到一個yield;停下,再次調用next()走下一個yield;

例2:復雜的例子

自動買股票,在股票價格低於某個價格自動買股票。

//獲取股票的價格
function* getStockPrice(stock){
  while(true){//無限循環
    yield Math.random()*100; //每次循環都會停住,返回0-100的一個數字
  }

}
var priceGenerator=getStockPrice("IBM"); //買IBM的股票,聲明成一個變量
var limitPrice=15;//價格低於15元才去買

var price=100;//起始的價格是100

while(price>limitPrice){//當價格大於限制的價格時 //價格小於15時跳出循環
  price=priceGenerator.next().value;//再去取一次價格
  console.log(`the generator return ${price}`); //打印一下取到的價格
}

console.log(`buying at ${price}`); //跳出循環時的price,即購買時的價格

 while(true)並沒有無限執行,只有條件滿足時才執行。 

了解更多參考:generator函數

三、TypeScript-解構表達式

通過表達式將對象(大括號聲明)或數組(中括號聲明)拆解成任意數量的變量

用對象或者數組的屬性或值初始化本地變量的時候,寫更少的代碼。

把對象的屬性值拆出來放到本地變量里邊去 。

typescript在線編輯器

例子1 對象的解構:

function getStock() {
    return {
        code: "IBM",
        price:100
    }
}

var { code, price } = getStock();
console.log(code);
console.log(price);

es6到es5的轉換

var { code, price } = getStock();//被轉換為如下3句代碼
var _a = getStock(), code = _a.code, price = _a.price;

注意的點:

function getStock() {
    return {
        code: "IBM",
        price: {
            price1: 200,
            price2:400
        }
    }
}

var { code: codeX, price:{price2} } = getStock();
console.log(codeX);//重命名
console.log(price2);//嵌套的值 析構里再寫個析構

例子2 數組的解構:

解構和rest操作符使用

var array1 = [1, 2, 3, 4,];
var [num1, num2,...others] = array1;
console.log(num1);
console.log(num2);
console.log(others);

析構表達式作為方法的參數

var array1 = [1, 2, 3, 4,];
var [num1, num2, ...others] = array1;
function doSomething([num1, num2, ...others]) {
    console.log(num1);
    console.log(num2);
    console.log(others);    
}

doSomething(array1);

 四,函數重載

先定義重載列表,再在一個最寬泛的類型中實現。

function add0(...rest:number[]):number
function add0(...rest:string[]):string
function add0(...rest:any[]):any{
    let first = rest[0];
    if(typeof first ==='string'){
        return rest.join('');
    }
    if(typeof first ==='number'){
        return rest.reduce((pre,cur)=>pre+cur)
    }
}

console.log(add0(1,2,3,4,5)); //15
console.log(add0('a','b','c'))  //abc

 

 

本文作者starof,因知識本身在變化,作者也在不斷學習成長,文章內容也不定時更新,為避免誤導讀者,方便追根溯源,請諸位轉載注明出處:http://www.cnblogs.com/starof/p/6961783.html 有問題歡迎與我討論,共同進步。

2017-06-08


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM