arrow function

  • 132
  • 0
  • ES6
  • 2018-08-27

arrow function

(1)直接回傳結果:(參數列表)=>(回傳值)

......如果我們的函式本身只是要回傳某個值的話,可以把 return 這個字省略掉

......小括號就直接寫回傳值

//ES6
var greeting = (n1, n2) => (n1+n2);
console.log(greeting( ));

//小括號可省略
var greeting = (n1, n2) => n1+n2;
console.log(greeting( ));

//傳統
var greeting = function (n1, n2){
    return "n1+n2";
}

(2) (參數列表)=>{ 函式內部程式 }

......大括號就像傳統的{ } 內寫法

function greeting ( ){
    console.log("hiiii");
}

var greeting = ( ) => {
    console.log("hiiii");
}

(3) 函數沒有參數或有兩個以上的參數時,都要加上括號( )​

......只有一個參數時,不需要使用括號

var greeting = number => "total:"+ number;
console.log(greeting("32"));

4.更簡短的寫法如下

// 正常寫法
var t = (someone) => {
  return someone + '去爬山'
}
console.log(t('小明'))

// 縮寫,單一行陳述不需要 {} ,single line arrow function didn't use an additional curly braces
var t = (someone) => someone + '去爬山'
console.log(t('小明'));

// 只有一個參數可以不加括號
var t = someone => someone + '去爬山'
console.log(t('小明'));

// 沒有參數時,一定要有括號
var t = () => '小明' + '去爬山'
console.log(t());

5.小地方也要注意一下,在大括號內的 {} 是需要自行加入 return,如果沒有傳入值則會出現 undefined

var t = (someone) => { someone + '去爬山' }
console.log(t('小明')) // undefined

//
const funcA = x => x + 1
const funcB = x => { x + 1 }

funcA(1) //2
funcB(1) //undefined

引用:

https://goo.gl/t9Y73x

https://goo.gl/NW3A5L

https://goo.gl/WKujSj