這個小專案是來自https://javascript30.com/的教學,點擊進去輸入email後就可以進入課程~!此為第四篇學習紀錄!一樣先附上程式碼Javascript。
這篇比較特別一些,影片的目的是練習陣列的各種用法,內容也相對的簡單了很多,以下會依照題目附上程式碼。
Javascript
const inventors = [
{ first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
{ first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
{ first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
{ first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
{ first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
{ first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
{ first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
{ first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
{ first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
{ first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
{ first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
{ first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
];
1. Filter the list of inventors for those who were born in the 1500’s
const fifteen = inventors.filter(item => item.year >= 1500 && item.year < 1600); console.table(fifteen)
2. Give us an array of the inventors’ first and last names
const names = inventors.map(item => item.first + ' ' + item.last); console.log(names)
3. Sort the inventors by birthdate, oldest to youngest
const elder = inventors.sort((a, b) => a.year > b.year ? 1 : -1); console.log(elder)
4. How many years did all the inventors live?
const period = inventors.reduce((a, b) => a + (b.passed - b.year), 0) console.log(period)
5. Sort the inventors by years lived
const lasting = inventors.sort((a, b) => (a.passed - a.year) > (b.passed - b.year) ? 1 : -1); console.table(lasting)
6. Sum up the instances of each of these
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck'];
const transportation = data.reduce((obj, item) => {
if (!obj[item]) {
obj[item] = 0
}
obj[item]++
return obj
}, {})
console.log(transportation)
學習重點
- 複習reduce的用法,起始點除了數值之外也可以採用空陣列或物件
- 複習sort的用法
- console.table也是不錯的表達方式