就决定是你了 - 阵列系列 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


<<:  评估管理者的绩效

>>:  [Day4] Tools And Environment

Day 04 HTML<表单标签>

表单标签主要功用是用来收集使用者资料 常用情况 : 注册页面... 主要由 表单域、表单元素、提示文...

[PHP]透过[jquery] 以 [Ajax]方式使用[Stored Procedure]取得[MSSQL]资料

网上找到的参考有点混乱,因此统整一下 使用环境: XAMPP 3.2.4 jquery.min.js...

用 Python 畅玩 Line bot - 21:LIFF(一)

LIFF 是一种 Line 提供让 line bot 可以不跳脱 Line 去开启网页的 API。 ...

Day 4. 关於.NET後端(2)

开开始学後端的人多少会听到ASP.NET、.NET Framework、.NET Core,但不清楚...

[Python 爬虫这样学,一定是大拇指拉!] DAY13 - HTTP / HTTPS (4)

本篇主要讲解 HTTP 状态码代表的意思。 主要是针对状态码的类别做讲解,所以不用担心会太多。且并不...