# 第三十九關:箭頭函式(arrow function)

情境:

技術主管看到小杰第 18 關的 Code 後,覺得非常吐血。

他說現在公司都用所謂的箭頭函式(arrow function),所以希望小杰也將 18 關的程式碼的 forEach 改為箭頭函式寫法,但小杰從來沒寫過什麼箭頭寫法,一起來幫幫小杰尋找資源吧!

# 問題

  1. 如果你是初學者,請回傳第 18 關的 forEach ,改用箭頭函式的寫法來撰寫
  2. 假使你已經會箭頭函式,請分享 arrow function 會如何影響到 this

# 文章分享

請將你紀錄的 HackMD 筆記,以及你找的技術文章分享到此,讓其他參賽者有更多資源可以參考

參考解答

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://fonts.googleapis.com/css2?family=Lato:wght@400;700&family=Noto+Sans+TC:wght@400;500;700&display=swap" rel="stylesheet">
  <title>Document</title>
</head>

<body>
  <ul class="list2">
    <li class="list-card">
      <h2></h2>
      <p></p>
    </li>
    <li class="list-card">
      <h2></h2>
      <p></p>
    </li>
  </ul>
</body>

</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
* {
  padding: 0;
  margin: 0;
  list-style: none;
  font-family: "Lato", "Noto Sans TC", sans-serif;
}
h2,
p {
  line-height: 2em;
  letter-spacing: 0.1em;
}
.list2 {
  list-style: none;
  margin: 0;
  padding: 0;
}

.list-card {
  background: orangered;
  width: 300px;
  margin: 0 auto;
  color: #fff;
  text-align: center;
  padding: 10px;
  margin-bottom: 30px;
}

.red {
  color: black;
  font-weight: bold;
  font-size: 20px;
}
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
let list2 = document.querySelector(".list2");
let data = [];
data.push({
  name: "廖洧杰",
  height: 178,
  weight: 70,
  BMI: 20.09,
  status: "體重正常"
});
data.push({
  name: "小乖",
  height: 120,
  weight: 46,
  BMI: 31.94,
  status: "重度肥胖"
});
data.push({
  name: "小麗",
  height: 140,
  weight: 50,
  BMI: 25.15,
  status: "體重過重"
});
data.push({
  name: "小新",
  height: 175,
  weight: 56,
  BMI: 18.29,
  status: "體重過輕"
});
data.push({
  name: "小華",
  height: 173,
  weight: 69,
  BMI: 23.5,
  status: "體重正常"
});

var str = "";
// data.forEach(function(item))
// arrow function 限制
// arrow function
data.forEach((item) => {
  let content = `<li class="list-card">
<h2>${item.name}</h2>
<p>你的身高是 ${item.height} 公分</p>
<p>你的體重是 ${item.weight} 公斤</p>
<p>BMI為 ${item.BMI}</p>
<p>狀態為 <span class = red>${item.status}</span></p>
</li>`;

  str += content;
});

list2.innerHTML = str;
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
最後更新: 8/3/2020, 2:04:27 AM