這篇文章主要介紹了2019 年編寫現代 JavaScript 代碼的5個小技巧,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧
內容基本是今年從其他大神的文章學習到的東西。分享給大家:
1 Array.includes 與條件判斷
一般我們判斷或用 ||
// condition function test(fruit) { if (fruit == "apple" || fruit == "strawberry") { console.log("red"); } }
如果我們有更多水果
function test(fruit) { const redFruits = ["apple", "strawberry", "cherry", "cranberries"]; if (redFruits.includes(fruit)) { console.log("red"); } }
2 Set 與去重
ES6 提供了新的數據結構 Set。它類似於數組,但是成員的值都是唯一的,沒有重複的值。Set 本身是一個構造函數,用來生成 Set 數據結構。
數組去重
const arr = [3, 5, 2, 2, 5, 5]; const unique = [...new Set(arr)]; // [3,5,2]
Array.from 方法可以將 Set 結構轉爲數組。我們可以專門編寫使用一個去重的函數
function unique(array) { return Array.from(new Set(array)); } unique([1, 1, 2, 3]); // [1, 2, 3]
字符去重
let str = [...new Set("ababbc")].join(""); console.log(str); // 'abc'
另外 Set 是如此強大,因此使用 Set 可以很容易地實現並集(Union)、交集(Intersect)和差集(Difference)。
let a = new Set([1, 2, 3]); let b = new Set([4, 3, 2]); // 並集 let union = new Set([...a, ...b]); // Set {1, 2, 3, 4} // 交集 let intersect = new Set([...a].filter(x => b.has(x))); // set {2, 3} // 差集 let difference = new Set([...a].filter(x => !b.has(x))); // Set {1}
3 Map 與字典類型數據
一般而已,JavaScript 實現字典數據是基於 Object 對象。但是 JavaScript 的對象的鍵只能是字符串。對於編程來說有很多不便。 ES6 提供了 Map 數據結構。它類似於 Object 對象,也是鍵值對的集合,但是“鍵”的範圍不限於字符串,各種類型的值,字符串、數值、布爾值、數組、對象等等都可以當作鍵。
const resultMap = new Map() .set(-1, {text:'小於',color:'yellow') .set(0, {text:'等於',color:'black') .set(1, {text:'大於',color:'green') .set(null,{text:'沒有物品',color:'red'}) let state = resultMap.get(null) // {text:'沒有物品',color:'red'}
Map 的遍歷順序就是插入順序
const map = new Map([["F", "no"], ["T", "yes"]]); for (let key of map.keys) { console.log(key); } // "F" // "T" for (let value of map.value()) { console.log(value); } // "no" // "yes"
4 函數式的方式處理數據
按照我的理解,函數式編程主張函數必須接受至少一個參數並返回一個值。所以所有的關於數據的操作,都可以用函數式的方式處理。
假設我們有這樣的需求,需要先把數組 foo 中的對象結構更改,然後從中挑選出一些符合條件的對象,並且把這些對象放進新數組 result 裏。
let foo = [ { name: "Stark", age: 21 }, { name: "Jarvis", age: 20 }, { name: "Pepper", age: 16 } ]; //我們希望得到結構稍微不同,age大於16的對象: let result = [ { person: { name: "Stark", age: 21 }, friends: [] }, { person: { name: "Jarvis", age: 20 }, friends: [] } ];
從直覺上我們很容易寫出這樣的代碼:
let result = []; //有時甚至是普通的for循環 foo.forEach(function(person){ if(person.age > 16){ let newItem = { person: person, friends: []; }; result.push(newItem); } })
使用函數式的寫法,可以優雅得多
let result = foo .filter(person => person.age > 16) .map(person => ({ person: person, friends: [] }));
數組求和
let foo = [1, 2, 3, 4, 5]; //不優雅 function sum(arr) { let x = 0; for (let i = 0; i < arr.length; i++) { x += arr[i]; } return x; } sum(foo); // => 15 //優雅 foo.reduce((a, b) => a + b); // => 15
5 compose 與函數組合
以下代碼稱爲組合 compose
const compose = function(f, g) { return function(x) { return f(g(x)); }; };
由於函數式編程大行其道,所以現在將會在 JavaScript 代碼看到大量的箭頭()=>()=>()=>的代碼。
ES6 版本 compose
const compose = (f, g) => x => f(g(x));
在 compose 的定義中, g 將先於 f 執行,因此就創建了一個從右到左的數據 流。這樣做的可讀性遠遠高於嵌套一大堆的函數調用.
我們選擇一些函數,讓它們結合,生成一個嶄新的函數。
reverse 反轉列表, head 取列表中的第一個元素;
const head = arr => arr[0]; const reverse = arr => [].concat(arr).reverse(); const last = compose(head, reverse); last(["jumpkick", "roundhouse", "uppercut"]); // "uppercut"
但是我們這個這個compose不夠完善,只能處理兩個函數參數。redux源碼有個很完備的compose函數,我們借鑑一下。
function compose(...funcs){ if (funcs.length === 0){ return arg => arg } if (funcs.length === 1 ){ return funcs[0] } return funcs.reduce((a,b)=>(...args) => a(b(...args))) }
有了這個函數,我們可以隨意組合無數個函數。現在我們增加需求,組合出一個lastAndUpper函數,內容是先reverse 反轉列表, head 取列表中的第一個元素, 最後toUpperCase大寫。
const head = arr => arr[0]; const reverse = arr => [].concat(arr).reverse(); const toUpperCase = str => str.toUpperCase(); const last = compose(head, reverse); const lastAndUpper = compose(toUpperCase, head, reverse,); console.log(last(["jumpkick", "roundhouse", "uppercut"])); // "uppercut" console.log(lastAndUpper(["jumpkick", "roundhouse", "uppercut"])) // "UPPERCUT"
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。