首次上傳:2017/05/23
延續[04 - Array Cardio Day 1]的Array各種操作,這次有5個範例。
[BLOG]
[DEMO]
- people:[ { name: ‘string’, year: number } ]
- comments:[ text: ‘string’, id: number } ]
- people是否有19歲以上的人
- People是否每個人都19歲以上
- 在comments中找到id是823423的資料
- 在comments中找到id是823423的資料索引值, 並透過索引值刪除這筆資料
題目:people是否有19歲以上的人?
解答:
const isAdult = people.some(person => ((new Date()).getFullYear()) - person.year >= 19);透過some()會將Array中的資料逐筆進行判斷,只要有一筆通過判斷則回傳true並結束。
題目:people是否每個人都19歲以上?
解答:
const allAdults = people.every(person => ((new Date()).getFullYear()) - person.year >= 19);every()會對Array中的每筆資料進行判斷,只要有一筆不符合則回傳false並結束。
與some()是相反操作的感覺。
題目:在comments中找到id是823423的資料
解答:
const comment = comments.find(comment => comment.id === 823423);find()會對Array中的資料逐筆進行判斷,返回第一筆符合條件的值,
若都沒有符合的值,將返回undefined。
題目:在comments中找到id是823423的資料索引值, 並透過索引值刪除這筆資料
解答:
const index = comments.findIndex(comment => comment.id === 823423);
const newComments = [
...comments.slice(0, index),
...comments.slice(index + 1)
];首先透過findIndex()對Array中的資料逐筆進行判斷,返回符合條件的索引值,
接著利用spared也就是省略符號...來進行展開陣列並透過slice()組合陣列,
...comments.slice(0, index),這段先將陣列開頭到索引值前的資料加進來,
...comments.slice(index + 1)這段則是將索引值+1後延續到陣列結束的資料加進來。
slice()的第一個參數是陣列索引的起點,第二個是終點(且不會被使用)無填寫則是到結束。
參閱:
MDN-Array.prototype.findIndex()
MDN-Spread syntax
MDN-Array.prototype.slice()