竹白記事本,Javascript 30,紀錄。
Javascript 30
陣列資料處理練習。
沒啥重點,就資料處理。
Array.prototype
filter()
map()
sort()
reduce()
共有三筆資料:
inventors
people
data
如果要查看資料, console.table()
會比 console.log()
來得直觀,它可將資料以表格的形式顯示,
Filter the list of inventors for those who were born in the 1500's.
從 inventors
篩選 15世紀(1500-1599)出生的。
filter()
會回傳一個新陣列,其條件是 return
後方為 true
的物件,很適合用在搜尋符合條件的資料。
使用 ES6 箭頭函式,更簡化
Give us an array of the inventors' first and last names.
將 inventors
的 first
與 last
組合成一個陣列。
map()
需要回傳一個值,他會透過函式內所回傳的值組合成一個新陣列。
undefined
map()
與 forEach()
差別:
forEach()
不會額外回傳值,只單純執行每個陣列內的物件或值。
如果要使用 forEach()
達成一樣功能,就要新增一個空陣列,並使用 push
將內容丟進空陣列。
Sort the inventors by birthdate, oldest to youngest.
將 inventor
依據生日由大至小排序。
sort()
方法會原地(in place)對一個陣列的所有元素進行排序,並回傳此陣列。
排序不一定是穩定的,各家瀏覽器都不同,可以參考 從 Array 的 sort 方法,聊到各瀏覽器的實作,沒想到 Chrome 和FireFox 的排序如此不同 這篇文章。
How many years did all the inventors live?
inventor
在世期間總和?
reduce()
方法將一個累加器及陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。
詳細可參考 JavaScript 中 reduce()
方法不完全指南。
不用 reduce()
的作法:
Sort the inventors by years lived.
將 inventor
依據年齡由大至小排序所有的。
create a list of Boulevards in Paris that contain 'de' anywhere in the name.
到 wiki
網頁,列出所有包含 'de'
的路名。
querySelectorAll()
出來的是 NodeList
,沒有 map()
方法,所以要先用 Array.from()
轉陣列。
include()
方法用來判斷一個陣列是否包含一個指定的值,根據情況,如果包含則返回 true
,否則返 false
。
Sort the people alphabetically by last name.
people
的 lastName
依據字母順序排序。
使用 split()
將名字拆開,再來判斷順序。
split()
方法使用指定的分隔符字符串將一個 String 對象分割成字串陣列,以將字符串分隔為子字符串,以確定每個拆分的位置。
Sum up the instances of each of these.
分別計算 data
內每個種類的數量。
首先將累計器的預設值設為空物件 {}
。
接著將物件建立出來,並加 1
。
但這樣子遇到重複的資料時,不會累加,只會重新將它重設為 0
並加 1
。
因此需要加上判斷式:
當 obj[item]
不存在就其建立並將值設為 0
。
這樣遇到重複的資料時,就不會又重設為 0
,而會累加次數。