解析與盤點數(shù)組array的5類22種方法
JS是唯一幾乎全面支持函數(shù)式編程的流行語言,而函數(shù)編程的起點是處理數(shù)組。因此,我們首先來盤點 array 數(shù)組的5類22種方法。
一、數(shù)組變形 Transform (函數(shù)范式的純函數(shù))
首先列出對數(shù)組變形操作的沒有side-effects的函數(shù)。
1) reduce 2) map 3) flat 4) flatMap 5) fill 6) forEach。其中 forEach 非 pure-function, 但屬于隱性迭代方法,故而分類在此。
- // 1.reduce
- let total = [ 0, 1, 2, 3 ].reduce( ( acc, cur ) => acc + cur,
- 0);
- // 2.map
- const maped = [4, 7, 9, 18].map(x => x * 2);
- // 3.flat
- let arr2 = [5, 2, 3].flat();
- // 4.flatMap
- [5, 8, 9, 6].flatMap(x => [[x * 2]]);
- // 5.fill 非純函數(shù),但是因為常用于構(gòu)建 range 用于迭代,因此分類到這里
- Array(5).fill(0)
- // 6.forEach 非純函數(shù),作為 map 處理有 side-effect 問題的替代方案。
- ['x', 'y', 'z'].forEach(el => console.log(el));
二、數(shù)組邏輯判斷 logic predicates(函數(shù)范式的純函數(shù))
函數(shù)范式的六個methods之后,我們繼續(xù)考察用于邏輯判斷的高階函數(shù):
1) filter 2) find 3) findIndex 4) includes 5) indexOf 6) some 7) every 以及我們可以自己構(gòu)建頗有幫助 range 與 not。
其中 include 是 find 應用于一個元素,而 indexOf 則是 findIndex 用于一個元素。
- // 1.filter
- [23, 76, 98, 101].filter( v => v > 30 && v < 100); //[ 76, 98 ]
- // 2.find 只需要單個元素則用 find
- [23, 76, 98, 101].find( v => v > 30 && v < 100); // 76
- // 3.findIndex 查找單個元素的index
- [23, 76, 98, 101].findIndex( v => v > 30 && v < 100); // 1
- // 4.includes 是 find 查找特定元素
- [23, 76, 98, 101].includes(77) // false
- // 5.indexOf 是 findIndex 查找某個特定元素的 index,返回值為 -1
- [23, 76, 98, 101].indexOf(77) // -1
- // 6.some
- [23, 76, 98, 101].some(v => v > 30 && v < 100) //true
- // 7.every
- [23, 76, 98, 101].every(v => v > 30 && v < 100) //false
三、非函數(shù)式的數(shù)組變形(純函數(shù))
以上兩組12個函數(shù)均為函數(shù)范式編程的純函數(shù)。接下來考察,其他對數(shù)組變形的純函數(shù)。(純函數(shù)是指沒有side-effect副作用的函數(shù)):
1) concat 2) join 3) slice 4) splice (非純函數(shù),將會修改原數(shù)組,放在此處只與slice對比,作為提醒)
- // 1.concat
- ['x', 'y', 'z'].concat([9, 8, 7]);
- // 2.join
- ['x', 'y', 'z'].join(",");
- // 3.slice
- ['x', 'y', 'z'].slice(1, 3);
- // 4.splice放到第四組中,此處只為提醒與slice相對比。
四、操作數(shù)據(jù)結(jié)構(gòu) (非純函數(shù))
Array可以作為兩種抽象結(jié)構(gòu)數(shù)據(jù)的載體:分別為 stack 和 queue。
1) push 2) pop 3) shift 4) unshift 5)splice(splice屬于特殊方法,因為更改了原數(shù)組,放在此處)
- let arr = [23, 76, 98, 101];
- // 1. push 元素添加到尾部
- > arr.push(120)
- 5
- > console.log(arr)
- [ 23, 76, 98, 101, 120 ]
- // 2.pop 以上 push 與 pop 組合構(gòu)建 stack 數(shù)據(jù)結(jié)構(gòu)。
- > arr.pop()
- 120
- > arr
- [ 23, 76, 98, 101 ]
- // 3.shift 從數(shù)組頭部取出元素,與push組合構(gòu)建 queue 數(shù)據(jù)結(jié)構(gòu)
- > arr.shift()
- 23
- > arr
- [ 76, 98, 101 ]
- // 4. unshift 從數(shù)組頭部添加元素
- > arr.unshift(59, 145)
- 5
- > arr
- [ 59, 145, 76, 98, 101 ]
- // 5.splice 為特殊的方法,用于拼接數(shù)組
- > arr.splice(1, 2, 55, 66, 77, 88)
- [ 145, 76 ]
- > arr
- [ 59, 55, 66, 77, 88, 98, 101 ]
五、數(shù)組排序 (非純函數(shù))
最后以無處而不在的排序收尾,無論是 sort 還是 reverse 都直接在原數(shù)組上修改,也就是 inplace 操作。
1) sort 2) reverse
- // 1. sort
- [23, 76, 98, 101].sort((x,y) => x - y)
- // 2.reverse
- [23, 76, 98, 101].reverse()
六、思維導圖總結(jié)