arrow function

2016-08-24  本文已影响50人  strong9527

本篇文章是es6学习笔记,将github上的文章翻译并整理一下;

箭头函数在许多现在语言中都已经支持了,javascript在es6当中也终于支持了


[1,2,3].map( num=> num * 2 ) 
// <- [2,4,6]

用es5表示

[1, 2, 3].map(function (num) { return num * 2 })
// <- [2, 4, 6]


[1,2,3].map(( num,index ) => num*2+index )
//<-[2,5,8,11]


[1,2,3,4].map(num => {
    var multiplier = 2 + num;
    return num * multiplier
})
// <- [3, 8, 15, 24]


[1, 2, 3, 4].map((num, index) => {
  var multiplier = 2 + index
  return num * multiplier
})
// <- [2, 6, 12, 20]


[1, 2, 3].map(n => { number: n })
// [undefined, undefined, undefined]

[1, 2, 3].map(n => { number: n, something: 'else' })
// <- SyntaxError

[1, 2, 3].map(n => ({ number: n }))
// <- [{ number: 1 }, { number: 2 }, { number: 3 }]

[1, 2, 3].map(n => ({ number: n, something: 'else' }))
/* <- [
  { number: 1, something: 'else' },
  { number: 2, something: 'else' },
  { number: 3, something: 'else' }]
*/


function Timer () {
  this.seconds = 0
  setInterval(() => this.seconds++, 1000)
}
var timer = new Timer()
setTimeout(() => console.log(timer.seconds), 3100)
// <- 3


上一篇下一篇

猜你喜欢

热点阅读