iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 4
0
Modern Web

JavaScript專案學習筆記系列 第 4

JavaScript專案學習筆記 -陣列方法練習 4/30天

  • 分享至 

  • xImage
  •  

感謝https://javascript30.com/的免費教程
學習點:
JS陣列

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 }
    ];

1.要過濾1500~1600年以外的人,使用filter

// 1. Filter the list of inventors for those who were born in the 1500's
    const bornFilter=inventors.filter(inventor=>(inventor.year>=1500 && inventor.year<=1600));
    console.table(bornFilter);
  1. Array.prototype.map():creates a new array with the results of calling a provided function on every element in this array. 要將first name和last name整合成一陣列,所以使用map()
// Array.prototype.map()
    // 2. Give us an array of the inventory first and last names
    const nameArray=inventors.map(inventor=>`${inventor.first} ${inventor.last}`);
    console.log(nameArray);

3.生日的排序,對於排序可直接使用sort

    // 3. Sort the inventors by birthdate, oldest to youngest
    const sortBirthday=inventors.sort((a,b)=>(a.year>b.year)?1:-1);
    console.table(sortBirthday);
    // Array.prototype.reduce()
    // 4. How many years did all the inventors live?
    const reduceInventor=inventors.reduce((a,year)=>{
      return a+(year.passed - year.year);}
      ,0);
    console.log(reduceInventor);

4.計算陣列中總數,要假設陣列中的物品都是不知道的,則a代表容器,b代表物品。還在摸索中(抓頭)

// 8. Reduce Exercise
    // 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 sumObject = data.reduce((a,b)=>{
      if(!a[b]) a[b]=0;
      a[b]++;
      return a;
    },{});
    console.log(sumObject);

上一篇
JavaScript專案學習筆記 -以JS操控CSS變數 3/30天
下一篇
JavaScript專案學習筆記 -Flex Panel 5/30天
系列文
JavaScript專案學習筆記7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言