1. 程式人生 > >typescript學習(2)---箭頭函式

typescript學習(2)---箭頭函式

ts中函式像其他值一樣可以當成引數傳來傳去。

箭頭函式可用來定義匿名函式:

1、對陣列中所有元素進行求和操作

var result = [1, 2, 3]
  .reduce((total, current) => total + current, 0);

console.log(result);

結果:6

2、獲取陣列中所有偶數

var even = [3, 1, 56, 7].filter(el => !(el % 2));

console.log(even);

結果:[56]

3、根據price和total屬性對陣列元素進行升序排列

var data = [{"price":3,"total":3},{"price":2,"total":2},{"price":1,"total":1}];
var sorted = data.sort((a, b) => {
  var diff = a.price - b.price;
  if (diff !== 0) {
    return diff;
  }
  return a.total - b.total;
});

console.log(sorted);

結果:

特性之一:執行上下文(this)指向為外層的程式碼:

function MyComponent() {
  this.age = 42;
  setTimeout(() => {
    this.age += 1;
    console.log(this.age);
  }, 100);
}

new MyComponent(); // 43 in 100ms.

結果:43

    當使用new操作符呼叫MyComponent函式的時候,程式碼中的this將會指向新建立的物件例項,在setTimeout的回撥函式中,箭頭函式會持有執行上下文(this),然後列印43。