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。