是 Ray 不是 Array

整理這些技術筆記真的很花時間,如果你願意 關閉 Adblock 支持我,我會把這份感謝轉換成更多「踩坑轉避坑」的內容給你!ヽ(・∀・)ノ

Advertisement
2021-10-24 JavaScript

JavaScript 核心觀念(68) - ES6 章節:箭頭函式 - 章節作業

前言

終於到了「ES6 章節:箭頭函式」結尾章節了,所以這邊就來看看這章節預計會出什麼作業吧。

章節作業

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var person = {
// 提款記錄
withdrawalRecord: [12, 45, 560, 120],
// 計算扣除的金額
calculate: () => {
var total = this.total
var sum = this.withdrawalRecord.reduce(function(acc, val) {
return acc + val
}, 0);
total = total - sum;
this.total = total;
},
// 剩餘的金額
total: 1000
}
person.calculate();
console.log(person.total);
// 問題:
// 1. 哪邊出錯了,請嘗試說明
// 2. 修正錯誤,並嘗試縮寫以上程式碼


Array.prototype.sumData = () => {
return this.reduce(function (acc, val) {
return acc + val
}, 0);
}
var arr = [1, 23, 5, 8, 52, 53, 63];
console.log(arr.sumData());
// 問題:
// 1. 哪邊出錯了,請嘗試說明
// 2. 修正錯誤,並嘗試縮寫以上程式碼

第一題

首先先來看第一道題目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var person = {
// 提款記錄
withdrawalRecord: [12, 45, 560, 120],
// 計算扣除的金額
calculate: () => {
var total = this.total
var sum = this.withdrawalRecord.reduce(function(acc, val) {
return acc + val
}, 0);
total = total - sum;
this.total = total;
},
// 剩餘的金額
total: 1000
}
person.calculate();
console.log(person.total);
// 問題:
// 1. 哪邊出錯了,請嘗試說明
// 2. 修正錯誤,並嘗試縮寫以上程式碼

首先先把握一個原則,箭頭函式沒有 this,所以 var total = this.total 必定會出現錯誤,因此會是一個 undefined,這樣子的話 this.withdrawalRecord 也是相同的原理,這樣子就會出現一種錯誤是 undefined 無法讀取的相關錯誤訊息,畢竟你可以試著思考一下 undefined 會有 reduce 方法嗎?

所以該段程式碼必須修改成以下,並且可以縮寫成以下

1
2
3
4
5
6
7
8
9
10
11
12
var person = {
// 提款記錄
withdrawalRecord: [12, 45, 560, 120],
// 計算扣除的金額
calculate() {
this.total -= this.withdrawalRecord.reduce((acc, val) => acc + val, 0);;
},
// 剩餘的金額
total: 1000
}
person.calculate();
console.log(person.total); // 263

第二題

第二題則是以下

1
2
3
4
5
6
7
Array.prototype.sumData = () => {
return this.reduce(function (acc, val) {
return acc + val
}, 0);
}
var arr = [1, 23, 5, 8, 52, 53, 63];
console.log(arr.sumData());

那麼重點一樣箭頭函式並沒有 this,因此寫在原型方法內必定會出現錯誤,所以要改寫成以下

1
2
3
4
5
Array.prototype.sumData = function () {
return this.reduce((acc, val) => acc + val, 0);
}
var arr = [1, 23, 5, 8, 52, 53, 63];
console.log(arr.sumData()); // 205

參考文獻

整理這些技術筆記真的很花時間,如果你願意 關閉 Adblock 支持我,我會把這份感謝轉換成更多「踩坑轉避坑」的內容給你!ヽ(・∀・)ノ

Advertisement

你的支持會直接轉換成更多技術筆記

如果我的筆記讓你少踩一個坑、節省 Debug 的時間,
也許你可以請我喝杯咖啡,讓我繼續當個不是 Array 的 Ray ☕

buymeacoffee | line | portaly

Terminal

分享這篇文章

留言

© 2025 Ray. All rights reserved.

Powered by Ray Theme