看完本文,希望可以寫出更加漂亮、簡潔、函式式的程式碼
reduce
reduce 可以用來彙總
資料
1 2 3 4 5 6 7 8 9 10 |
const customer = [ {id: 1, count: 2}, {id: 2, count: 89}, {id: 3, count: 1} ]; const totalCount = customer.reduce((total, item) => total + item.count, 0 // total 的初始值 ); // now totalCount = 92 |
把一個物件陣列變成一個以陣列中各個物件的 id 為屬性名,物件本身為屬性值的物件。haoduoshipin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
let products = [ { id: '123', name: '蘋果' }, { id: '345', name: '橘子' } ]; const productsById = products.reduce( (obj, product) => { obj[product.id] = product return obj }, {} ); console.log('result', productsById); |
map
map 可以理解為是陣列的轉換器,依次對陣列中的每個元素做變換進而得到一個新的陣列。
1 2 3 4 |
const integers = [1, 2, 3, 4, 6, 7]; const twoXIntegers = integers.map(i => i*2); // twoXIntegers are now [2, 4, 6, 8, 12, 14] // integers陣列並不會受到影響 |
find
篩選出陣列中的個別
元素
1 2 3 4 5 6 |
const posts = [ {id: 1, title: 'Title 1'}, {id: 2, title: 'Title 2'}, ]; // find the title of post whose id is 1 const title = posts.find(p => p.id === 1).title; |
唉~ 使用了半年的 es6才發現有這麼好用的東西,譯者傻缺還像下面這麼寫過呢
1 2 3 4 5 6 |
const posts = [ {id: 1, title: 'Title 1'}, {id: 2, title: 'Title 2'}, ]; const title = posts.filter(item => item.id === 1)[0].title; |
filter
篩選出陣列中某些
符合條件的元素組成新的陣列
1 2 3 |
const integers = [1, 2, 3, 4, 6, 7]; const evenIntegers = integers.filter(i => i % 2 === 0); // evenIntegers are [2, 4, 6] |
請大家自行思考下filter
和find
的區別
陣列concat
1 2 3 4 |
const arr1 = [1, 2, 3, 4, 5]; const arr2 = [6, 7, 8, 9, 0]; const arrTarget = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] |
物件操作
1 2 3 4 5 6 7 8 9 |
function operation(query, option = {}) { const param = {...query, ...option}; // .... return param; } let opt = {startTime: 123455555, endTime: 113345555}; let q = {name: '一步', age: 'xxx'}; operation(q, opt); // {name: "一步", age: "xxx", startTime: 123455555, endTime: 113345555} |
物件是引用傳參的,所以函式內部應該儘可能的保證傳入的引數不受到汙染。
為物件動態地新增欄位
1 2 3 4 |
const dynamicKey = 'wearsSpectacles'; const user = {name: 'Shivek Khurana'}; const updatedUser = {...user, [dynamicKey]: true}; // updatedUser is {name: 'Shivek Khurana', wearsSpectacles: true} |
將物件轉換為query字串
1 2 3 4 5 6 7 8 9 |
const params = {color: 'red', minPrice: 8000, maxPrice: 10000}; const query = '?' + Object.keys(params) .map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]) ) .join('&') ; // encodeURIComponent encodes special characters like spaces, hashes // query is now "color=red&minPrice=8000&maxPrice=10000" |
得到物件陣列的元素 index
1 2 3 4 5 6 7 8 |
const posts = [ {id: 13, title: 'Title 221'}, {id: 5, title: 'Title 102'}, {id: 131, title: 'Title 18'}, {id: 55, title: 'Title 234'} ]; // to find index of element with id 131 const requiredIndex = posts.map(p => p.id).indexOf(131); |
更加優雅的寫法呱呱呱提供:
1 2 3 4 5 6 7 |
const posts = [ {id: 13, title: 'Title 221'}, {id: 5, title: 'Title 102'}, {id: 131, title: 'Title 18'}, {id: 55, title: 'Title 234'} ]; const index = posts.findIndex(p => p.id === 131) |
刪除物件的某個欄位
1 2 3 4 5 6 7 8 9 10 |
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'}; const userWithoutPassword = Object.keys(user) .filter(key => key !== 'password') .map(key => {[key]: user[key]}) .reducer((accumulator, current) => ({...accumulator, ...current}), {} ) ; // userWithoutPassword becomes {name: 'Shivek Khurana', age: 23} |
這裡我認為原作者有點為了函數語言程式設計而函式式了,下面是我的解決方案:
1 2 3 4 |
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'}; const newUser = {...user}; delete newUser.password; // {name: "Shivek Khurana", age: 23} |
以上程式碼片段的共同原則:不改變原資料。希望大家的程式碼都可以儘可能的簡潔,可維護。