箭頭函式 Arrow Function


Posted by Calon on 2022-04-26

// 箭頭函式
const a = () => {
    console.log('hi');
};
const b = (a, b) => {
    console.log(a, b);
};

// 當參數只有一個時,可省略()
const c = a => {
    console.log(a);
};

// 當內容只有一行表達式時,可省略{}
const d = a => a;
d(1); // return 1
const f = a => console.log(a); 
f(2) // 2

// 範例:
const ary = [1, 2, 3];

// 傳統
const arrowFilter = ary.filter(function (item){
    return item < 3;
}); // [1, 2]

// 箭頭
const arrowFilter = ary.filter(item => item < 3);  // [1, 2]


※要注意的地方:

  1. 使用箭頭函式時,this 指向會跟傳統函式不一樣。
  2. 沒有 arguments 參數。
function num(){
    console.log(arguments);
}
num(1,2,3,4,5); // Arguments(5) [1, 2, 3, 4, 5, callee: ƒ, Symbol(Symbol.iterator): ƒ]

const nums = () => {
    console.log(arguments);
}
nums(1,2,3,4,5); // Uncaught ReferenceError: arguments is not defined

參考資料

#javascript #Arrow Function







Related Posts

筆記:我知道你懂 hoisting,可是你了解到多深?

筆記:我知道你懂 hoisting,可是你了解到多深?

《鳥哥 Linux 私房菜:基礎篇》Chapter 06 - Linux 的檔案與目錄管

《鳥哥 Linux 私房菜:基礎篇》Chapter 06 - Linux 的檔案與目錄管

用 PHP 做出 API

用 PHP 做出 API


Comments