iT邦幫忙

0

JS ES6 箭頭函式常見問題 DAY74

  • 分享至 

  • twitterImage
  •  

箭頭函式常見問題

若要回傳物件
需用一個括號包住

const fn = () => ({
    data: 1
});
console.log(fn());

傳統函式

let num = 0;
const fn = num || function(){ return 1}
console.log(fn());

改成 箭頭函式
(若搭配判斷式 箭頭函式需包在括號裡面)

let num = 0;
const fn = num || (()=>  2)
console.log(fn());

箭頭函式實戰用法

這裡提供一篇陣列各種方法的文章
https://wcc723.github.io/javascript/2017/06/29/es6-native-array/

  • 陣列雙倍

map: 將原本所有陣列內容一一取出,然後透過回傳套用在一個新陣列上
https://ithelp.ithome.com.tw/upload/images/20201025/20123039NMHMY9bFww.jpg

傳統函式

const arr = [10,50,26,44,18,152,105]
const arrDouble = arr.map(function(item){
    return item * 2;
})
console.log(arrDouble); // 20 100 52 88 36 304 210

箭頭函式

const arr = [10,50,26,44,18,152,105]
const arrDouble = arr.map( item => item * 2);
console.log(arrDouble); // 20 100 52 88 36 304 210

  • 平均數

傳統函式

const average = function(){
    // Array.from 轉為純陣列
    const num = Array.from(arguments);
    const total = num.reduce(function(acc,val){
        return acc + val;
    },0)
    console.log(total); // 15 
    return total / num.length; // 3
}
console.log(average(1,2,3,4,5));

箭頭函式

const average = (...num) => num.reduce((acc,val) => acc + val ,0) / num.length
console.log(average(1,2,3,4,5));

那今天的介紹就到這裡
若有任何問題 或 內容有誤
都可以跟我說唷/images/emoticon/emoticon41.gif


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言