延续前一天的阵列特训,今天继续认识四个不会改变原阵列
的阵列方法吧,每个阵列方法都可以传入一个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值 |
以下是篮球员的得分及场上表现纪录,接下来我们就使用学过的阵列方法来破关吧!
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 }
]
const result = players.some(player => player.foul >= 5)
console.log(result) //true
注:因为回传的是整笔资料,但裁判只要知道是谁要下场,所以用物件取值的方式印出名字就好。
const result = players.find(player => player.foul >= 5);
console.log(result.name); // 赤木刚宪
注:如果使用Array.prototype.some(),因为只要部分符合就会回传true,所以必须使用Array.prototype.every()确认是每一位都有得分才回传true。
const result = players.every(player => player.points > 0);
console.log(result); //false
注:因为程序世界的index起始值是0,但人类世界习惯从1开始计数,所以对index值加1。
const index = players.findIndex(player => player.name === '三井寿');
const order = index + 1;
console.log(order); // 5
上述的挑战就让各位展现实力了~(其实是自己解不出来哈哈哈)
明天我们要一次认识会改变原阵列的Array Method罗~
参考资料:
Array Methods - MDN
>>: [Day4] Tools And Environment
表单标签主要功用是用来收集使用者资料 常用情况 : 注册页面... 主要由 表单域、表单元素、提示文...
网上找到的参考有点混乱,因此统整一下 使用环境: XAMPP 3.2.4 jquery.min.js...
LIFF 是一种 Line 提供让 line bot 可以不跳脱 Line 去开启网页的 API。 ...
开开始学後端的人多少会听到ASP.NET、.NET Framework、.NET Core,但不清楚...
本篇主要讲解 HTTP 状态码代表的意思。 主要是针对状态码的类别做讲解,所以不用担心会太多。且并不...