iT邦幫忙

2021 iThome 鐵人賽

DAY 4
0
Modern Web

前端藏寶圖系列 第 4

就決定是你了 - 陣列系列 II

延續前一天的陣列特訓,今天繼續認識四個不會改變原陣列的陣列方法吧,每個陣列方法都可以傳入一個callback function,其參數值一致都是:

1. 目前迭代處理的元素
2. 目前迭代處理的元素的索引值
3. 呼叫該方法的陣列
使用目的 方法名稱 回傳值
確認陣列中是否有資料符合某個條件 Array.prototype.some() 只要陣列中其中一個元素符合callback function規則,就回傳true,否則回傳false (布林值)
確認陣列每筆資料都符合某個條件 Array.prototype.every() 所有陣列元素都須符合callback function 中的條件才回傳true,否則回傳false (布林值)
需要第一筆符合條件的資料細節 Array.prototype.find() 第一個符合callback function規則的元素值
需要第一筆符合條件的資料index值 Array.prototype.findIndex() 第一個符合callback function規則的元素的index值

以下是籃球員的得分及場上表現紀錄,接下來我們就使用學過的陣列方法來破關吧!/images/emoticon/emoticon75.gif

let players = [
  { name: '櫻木花道', points: 0, rebound: 0, assist: 0, steal: 0, foul: 4 },
  { name: '流川楓', points: 30, rebound: 6, assist: 3, steal: 3, foul: 1 },
  { name: '赤木剛憲', points: 16, rebound: 10, assist: 0, steal: 0, foul: 5 },
  { name: '宮城良田', points: 6, rebound: 0, assist: 7, steal: 6, foul: 3 },
  { name: '三井壽', points: 21, rebound: 4, assist: 3, steal: 0, foul: 0 },
  { name: '仙道彰', points: 32, rebound: 4, assist: 8, steal: 0, foul: 2 },
  { name: '牧紳一', points: 17, rebound: 0, assist: 11, steal: 0, foul: 1 },
  { name: '魚住純', points: 13, rebound: 13, assist: 1, steal: 0, foul: 4 }
]

關卡1: 球員中是否有人已經五犯得離場的?

const result = players.some(player => player.foul >= 5)

console.log(result) //true

關卡2: 找出球員中第一位五犯得離場的?

註:因為回傳的是整筆資料,但裁判只要知道是誰要下場,所以用物件取值的方式印出名字就好。

const result = players.find(player => player.foul >= 5);

console.log(result.name); // 赤木剛憲

關卡3: 每位球員在賽季中是否都有得分呢?

註:如果使用Array.prototype.some(),因為只要部分符合就會回傳true,所以必須使用Array.prototype.every()確認是每一位都有得分才回傳true。

const result = players.every(player => player.points > 0);

console.log(result); //false

關卡4: 三井壽在球員名單中是排第幾位呢?

註:因為程式世界的index起始值是0,但人類世界習慣從1開始計數,所以對index值加1。

const index = players.findIndex(player => player.name === '三井壽');
const order = index + 1;

console.log(order); // 5

/images/emoticon/emoticon69.gif

挑戰題: 找出賽季中總得分最高且表現最佳(籃板球/抄截/助攻次數加總最高)的球員作為MVP

上述的挑戰就讓各位展現實力了~(其實是自己解不出來哈哈哈
明天我們要一次認識會改變原陣列的Array Method囉~


參考資料:
Array Methods - MDN


上一篇
就決定是你了 - 陣列系列I
下一篇
就決定是你了 - 陣列系列III
系列文
前端藏寶圖30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言