iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 7
0
Modern Web

一起挑戰 JavaScript 30 吧!系列 第 7

JS30 Day 7 - Array Cardio Day 2

頁面連結(請打開 console 查看)

今天不寫程式,學習 (或是複習) 一些 Array methods 吧!

先列出本篇所涵蓋的 methods

  • some()
  • every()
  • find()
  • findIndex()
  • splice()
  • slice()

開始寫程式碼

我們有兩個陣列要處理:

const people = [
  { name: 'Wes', year: 1988 },
  { name: 'Kait', year: 1986 },
  { name: 'Irv', year: 1970 },
  { name: 'Lux', year: 2015 }
];

const comments = [
  { text: 'Love this!', id: 523423 },
  { text: 'Super good', id: 823423 },
  { text: 'You are the best', id: 2039842 },
  { text: 'Ramen is my fav food ever', id: 123523 },
  { text: 'Nice Nice Nice!', id: 542328 }
];

Q1: people 陣列中是否有一人以上 19 歲以上?

要檢查陣列項目是否有 “一項以上” 符合,可以使用 some() 來處理,函式只會 return true 或是 false

const isAdults = people.some(person => ((new Date()).getFullYear() - person.year) >= 19);
console.log(isAdults);  // true

如果不用 some() 的話,使用 find()filter()或許也都是可行的做法 (但相對麻煩一些)

Q2: people 陣列中是否有全部的人都 19 歲以上?

若要檢查陣列中是否 “每項” 都符合條件,可以使用 every() ,該函式如 some() 只會 return true or false

const allAdults = people.every(person => ((new Date()).getFullYear() - person.year) >= 19);
console.log(allAdults);  // false

Q3: 從 comments 陣列中找到 id 為 823423 的項目

這裡有很多做法,可以使用 forEach 搭配 includesfilter()等等... 但搜尋目標如果只有一項就是使用 find() 的絕佳時機了!find() 會 return 被篩選出的 “第一項”

let foundId = comments.find(comment => comment.id === 823423);
console.log(foundId.text);  // "Super good"

Q4: 從 comments 陣列刪除 id 為 823423 的項目

這裡可以拆分成兩部分,找出該項與刪除該項

找出該項

find()搜尋目標只有一個,但這裡可以用 findIndex(),該函式會 return 被篩選出的 “第一項” 的 index number

const foundIdIndex = comments.findIndex(comment => comment.id === 823423);

刪除該項

找出來了但要如何刪除?有兩種辦法,一種是透過 splice() ,而另一種是透過 slice() 另組新陣列

先看第一種 splice()

使用 splice()

splice 可以用於刪除或是插入,但這裡我們只用得到刪除的部分

const newComments = comments.splice(foundIdIndex, 1);

第一個參數是開始的 index number,第二個參數代表要除去的數量;splice()slice() 其實蠻像的,無論是用法或長相,但用法其實不太一樣,詳情就請見 MDN 說明了

透過 slice() 另組新陣列

這個方法我也是第一次嘗試,結合了展開運算式(spread operator) 與 slice()

const newComments = [
  ...comments.slice(0, foundIdIndex),
  ...comments.slice(foundIdIndex + 1)
];

概念是將欲刪除的該項排除複製其他項目到新陣列 newComments
也就是說:

  • ...comments.slice(0, foundIdIndex) 表示的是 comments[foundIdIndex] 之前的所有項目 (不包含 comments[foundIdIndex])
  • ...comments.slice(foundIdIndex + 1) 表示的是 comments[foundIdIndex] 之後的所有項目 (不包含 comments[foundIdIndex])

... 即 spread syntex,能夠展開陣列中的內容,可以試試看去掉 ... ,會發現結果會是 [Array(1), Array(3)] ,也就是陣列裡面又包著陣列;而 ... 所做到就是陣列中的 “內容” 而不是 “整個陣列”

Reference


上一篇
JS30 Day 6 - Type Ahead
下一篇
JS30 Day 8 - Fun with HTML5 Canvas
系列文
一起挑戰 JavaScript 30 吧!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言