箭頭函式實戰用法

Abby 旦旦
3 min readSep 7, 2021

--

實戰一
搭配陣列方法

const arr = [1,2,3,4,5];傳統寫法
const arrDouble = arr.map(function(num){
return num * 2;
});
箭頭函式寫法
const arrDouble = arr.map(num => num * 2);
console.log(arrDouble); // 得到[2,4,6,8,10]

map() = 適合用在陣列所有的值都需要做調整的時候使用。

實戰二
計算平均值

傳統寫法
const average = function () {
const nums = Array.from(arguments);
const total = nums.reduce(function (acc, val) {
return acc + val
}, 0);
console.log(total);
return total / nums.length;
}
箭頭函式寫法
const average = (...num) => num.reduce((acc, val) => acc + val, 0) / num.length;
console.log(average(1, 2, 3, 4, 5, 10));

reduce() = 可以與前一個回傳的值再次作運算。

參數包含以下:

· accumulator
前一個參數,如果是第一個陣列的話,值是以另外傳入或初始化的值
· currentValue 當前變數
· currentIndex 當前索引
· array 全部陣列

實戰三
物件內的 this

傳統寫法
const person = {
data: {
},
getData: function() {
const vm = this;
$.ajax({
url: 'https://randomuser.me/api/',
dataType: 'json',
success: function(data) {
console.log(data);
vm.data = data.results[0];
console.log('person.data', person.data);
}
});
}
}
person.getData();
箭頭函式寫法
const person = {
data: {
},
getData: function() {
// 註解 const vm = this;
$.ajax({
url: 'https://randomuser.me/api/',
dataType: 'json',
success: (data) => {
console.log(data);
this.data = data.results[0];
console.log('person.data', person.data);
}
});
}
}
person.getData();

在此由於 success 改成箭頭函式寫法,所以沒有自己的 this,因此向外尋找時,參考了父層 this 也就是 getData。

因此 this 將會從此開始計算,那在下方 getData 是基於在 person 所呼叫,因此 this 就會指向到 person,那麼就不會指向 getData

補充資源:

一個可以告訴你js各種小技巧的chrome擴充插件(幾乎都是用es6寫法)
https://30secondsofknowledge.com/

--

--

Abby 旦旦
Abby 旦旦

Written by Abby 旦旦

從零開始轉職網頁設計,正在緩慢朝前端工程邁進中!偶爾會發一些讀後感和UI分享,ㄚㄚ!

No responses yet