內(nèi)容基本是今年從其他大神的文章學(xué)習(xí)到的東西。分享給大家:
1 Array.includes 與條件判斷
一般我們判斷或用 ||
// conditionfunction 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 提供了新的數(shù)據(jù)結(jié)構(gòu) Set。它類似于數(shù)組,但是成員的值都是唯一的,沒有重復(fù)的值。Set 本身是一個(gè)構(gòu)造函數(shù),用來生成 Set 數(shù)據(jù)結(jié)構(gòu)。
數(shù)組去重
const arr = [3, 5, 2, 2, 5, 5];const unique = [...new Set(arr)];// [3,5,2]
Array.from 方法可以將 Set 結(jié)構(gòu)轉(zhuǎn)為數(shù)組。我們可以專門編寫使用一個(gè)去重的函數(shù)
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 是如此強(qiáng)大,因此使用 Set 可以很容易地實(shí)現(xiàn)并集(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 與字典類型數(shù)據(jù)
一般而已,JavaScript 實(shí)現(xiàn)字典數(shù)據(jù)是基于 Object 對象。但是 JavaScript 的對象的鍵只能是字符串。對于編程來說有很多不便。 ES6 提供了 Map 數(shù)據(jù)結(jié)構(gòu)。它類似于 Object 對象,也是鍵值對的集合,但是“鍵”的范圍不限于字符串,各種類型的值,字符串、數(shù)值、布爾值、數(shù)組、對象等等都可以當(dāng)作鍵。
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"http:// "T"for (let value of map.value()) { console.log(value);}// "no"http:// "yes"4 函數(shù)式的方式處理數(shù)據(jù)
按照我的理解,函數(shù)式編程主張函數(shù)必須接受至少一個(gè)參數(shù)并返回一個(gè)值。所以所有的關(guān)于數(shù)據(jù)的操作,都可以用函數(shù)式的方式處理。
假設(shè)我們有這樣的需求,需要先把數(shù)組 foo 中的對象結(jié)構(gòu)更改,然后從中挑選出一些符合條件的對象,并且把這些對象放進(jìn)新數(shù)組 result 里。
新聞熱點(diǎn)
疑難解答
圖片精選