原文首發於Lodash源碼講解javascript
這是咱們閱讀Lodash源碼的第3篇博客,在這篇文章裏咱們來學習一下Lodash的compact
方法。java
compact
函數內部沒有依賴別的函數,讓咱們先來看一下compact
函數的源碼。git
/** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * compact([0, 1, false, 2, '', 3]) * // => [1, 2, 3] */ function compact(array) { let resIndex = 0 const result = [] if (array == null) { return result } for (const value of array) { if (value) { result[resIndex++] = value } } return result } export default compact
首先咱們先說一下這個函數的做用,這個函數接收一個數組做爲參數;而後將數組中全部經過布爾轉換能夠變爲false
的值去除;從而生成一個新的數組。github
那麼那些值經過布爾轉換會變爲false
呢;這些值有:0
,""
,false
,null
,undefined
,NaN
。數組
由於這個函數比較簡單,咱們就不劃分步驟了,直接進行講解;首先咱們初始化了兩個變量,resIndex
用來表示咱們返回的數組的索引;result
是咱們新建立的一個數組,這個數組就是咱們要返回的數組;接下來,若是傳遞的數組爲空,咱們直接返回一個空的數組;接下來就是使用ES6
新的語法,for...of
對傳遞的數組進行循環,將可以經過布爾轉化爲false
的值去除,而後就獲取到了咱們想要的結果。app
那麼,接下來咱們首先把這個源碼部分實現一遍;雖然簡單,可是仍是要本身敲一遍代碼的;切記不要眼高手低。compact是我本身又從新實現一遍的代碼。jsp
接下來咱們考慮一下,若是咱們不使用for...of
來循環數組,而是使用數組的map
方法,或者是使用while
進行數組的循環;它們的效率有多大的差別?讓咱們來實踐一下,首先是使用map
方法,咱們使用以下的代碼來進行測試:函數
// 使用數組原生的map方法 function compact(array) { // 判斷array是否爲空 if(array == null) { return []; } let result = []; array.map((value) => { if(value) { result.push(value); } }); return result; }
再接着咱們使用while
進行數組的循環,使用以下的代碼進行測試:性能
// 使用while進行數組的循環 function compact(array) { // 判斷array是否爲空 if(array == null) { return []; } let result = []; let index = 0; let resIndex = 0; let value; const length = array.length; while(index < length) { value = array[index]; if(value) { result[resIndex++] = value; } index++; } return result; }
我將這兩個方法都添加到以前的那個例子中了,你們能夠點擊這裏查看。學習
接下來咱們就要進行性能的測試了,我寫了一個測試的用例;你們能夠點擊這裏查看。通過屢次測試發現,使用lodash的compact
方法和使用while
進行數組循環的compact方法的性能都仍是不錯的,使用map
進行數組循環的compact方法性能最差;可是使用map
方法的compact方法代碼量是比較少的。
性能比較的圖以下圖所示:
compact
方法性能比較好的一次測試:while
進行數組循環的compact方法性能比較好的一次測試: