直接返回表达式
var odds = evens.map(v => v + 1);
var nums = evens.map((v, i) => v + i);
var odds = evens.map(function (v) {
return v + 1;
});
var nums = evens.map(function (v, i) {
return v + i;
});
包含语句
nums.forEach(v => {
if (v % 5 === 0)
fives.push(v);
});
nums.forEach(function (v) {
if (v % 5 === 0) fives.push(v);
});
包含this
不用修正箭头函数的this,this自动指向所在的上下文对象
var bob = {
_name: "Bob",
_friends: [],
printFriends() {
this._friends.forEach(f =>
console.log(this._name + " knows " + f));
}
};
对比非箭头函数的写法会更容易理解一些:
var bob = {
_name: "Bob",
_friends: [],
printFriends: function printFriends() {
var _this = this; // 需要修正this指向
this._friends.forEach(function (f) {
return console.log(_this._name + " knows " + f);
});
}
};
转载自:https://www.jianshu.com/p/6dee2632a717