const inventors = [ { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 }, { first: 'wawa', last: 'fs', year: 1830, passed: 1905 }, { first: 'grvd', last: 'xcvxcv', year:1900, passed: 1977 }, { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 } ]; 複製代碼
['Albert, Einstein', 'wawa, fs', 'grvd, xcvxcv', 'Hanna, Hammarström'] 複製代碼
function bornyear(inventor) { return inventor.year >= 1800 && inventor.year < 1900; } var fifteen = inventors.filter(bornyear); console.log(fifteen); // 可簡化爲 const fifteen = inventors.filter(inventor => (inventor.year >= 1500 && inventor.year < 1600)); 複製代碼
首先經過一個函數bornyear,在函數中進行條件的篩選,篩選出生日期在19世紀的發明家,返回的是true或者false。以後經過調用filter方法,將數組inventors裏面的元素進行是否符合函數bornyear的篩選條件進行過濾。最後返回的是符合條件的一個結果數組以下。javascript
[ {first: "Albert", last: "Einstein", year: 1879, passed: 1955}, {first: "wawa", last: "fs", year: 1830, passed: 1905}, {first: "Hanna", last: "Hammarström", year: 1829, passed: 1909} ] 複製代碼
const fullnames = inventors.map(inventor => `${inventor.first} ${inventor.last}`); console.log(fullnames); 複製代碼
打印出來的結果爲:java
["Albert Einstein", "wawa fs", "grvd xcvxcv", "Hanna Hammarström"] // inventors.map後面經過傳入原操做數組,而後再進行字符串拼接的處理。最終返回的數組是一個通過處理以後的新數組 複製代碼
function compare(a, b) { if (a < b) { // 按某種排序標準進行比較, a 小於 b return -1; } if (a > b) { return 1; } // 當a === b 時候 return 0; } 複製代碼
要比較數字而非字符串,比較函數能夠簡單的以 a 減 b,以下的函數將會將數組升序排列:數組
function compareNumbers(a, b) { return a - b; } 複製代碼
針對第三題,咱們就能夠簡單用加減比較瀏覽器
const birthdate = inventors.sort((inventora, inventorb) => (inventorb.year - inventora.year)); console.log(birthdate) 複製代碼
打印出來的結果爲:markdown
[ {first: "grvd", last: "xcvxcv", year: 1900, passed: 1977}, {first: "Albert", last: "Einstein", year: 1879, passed: 1955}, {first: "wawa", last: "fs", year: 1830, passed: 1905}, {first: "Hanna", last: "Hammarström", year: 1829, passed: 1909} ] 複製代碼
const totalyears = inventors.reduce((total, inventor) => { return total + (inventor.passed - inventor.year); }, 0); console.log(totalyears); 複製代碼
能夠將數組進行便利,按照篩選條件找出所要累加的值。返回的是累加的結果函數