loadsh簡介

loadsh簡介

      Lodash是一個一致性、模塊化、高性能的 JavaScript 實用工具庫。Lodash 通過降低 array、number、objects、string 等等的使用難度從而讓 JavaScript 變得更簡單。
Lodash 的模塊化方法 非常適用於:

  • 遍歷 array、object 和 string
  • 對值進行操作和檢測
  • 創建符合功能的函數

1、 lodash的引用

npm i -g npm
npm i --save lodash
import _ from 'lodash'

2、 lodash的常用方法

  1. 數組 Array

    • _.difference(array, [values])
      創建一個具有唯一array值的數組,每個值不包含在其他給定的數組中。(愚人碼頭注:即創建一個新數組,這個數組中的值,爲第一個數字(array 參數)排除了給定數組中的值。)該方法使用 SameValueZero做相等比較。結果值的順序是由第一個數組中的順序確定。

      如: _.difference([2, 1, 1994], [4, 2]);
       // => [1, 1994] 
    • _.remove(array, [predicate=_.identity])
      移除數組中predicate(斷言)返回爲真值的所有元素,並返回移除元素組成的數組。predicate(斷言) 會傳入3個參數: (value, index, array)。

       如:var array = [1, 2, 3, 4];
       var evens = _.remove(array, function(n) {
       return n % 2 == 0;
       });
       console.log(array);
       // => [1, 3]
        
       console.log(evens);
       // => [2, 4]
      
      
    • _.uniq(array)
      創建一個去重後的array數組副本。使用了 SameValueZero 做等值比較。只有第一次出現的元素纔會被保留。

       如:_.uniq([2, 1, 2]);
       // => [2, 1]
      
    • _.last(array)
      獲取array中的最後一個元素。

       如:_.last([1, 2, 3]);
       // => 3
  2. 集合 Collection

    • _.forEach(collection, [iteratee=_.identity])
      調用 iteratee 遍歷 collection(集合) 中的每個元素, iteratee 調用3個參數: (value, index|key, collection)。 如果迭代函數(iteratee)顯式的返回 false ,迭代會提前退出。

        如:_([1, 2]).forEach(function(value) {
          console.log(value);
        });
        // => Logs `1` then `2`.
         
        _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
          console.log(key);
        });
        // => Logs 'a' then 'b' (iteration order is not guaranteed).
    • _.filter(collection, [predicate=_.identity])
      遍歷 collection(集合)元素,返回 predicate(斷言函數)返回真值 的所有元素的數組。 predicate(斷言函數)調用三個參數:(value, index|key, collection)。

        如:var users = [
          { 'user': 'barney', 'age': 36, 'active': true },
          { 'user': 'fred',   'age': 40, 'active': false }
        ];
         
        _.filter(users, function(o) { return !o.active; });
        // => objects for ['fred']
         
        // The `_.matches` iteratee shorthand.
        _.filter(users, { 'age': 36, 'active': true });
        // => objects for ['barney']
         
        // The `_.matchesProperty` iteratee shorthand.
        _.filter(users, ['active', false]);
        // => objects for ['fred']
         
        // The `_.property` iteratee shorthand.
        _.filter(users, 'active');
        // => objects for ['barney']
      
      
    • _.groupBy(collection, [iteratee=_.identity])
      創建一個對象,key 是 iteratee 遍歷 collection(集合) 中的每個元素返回的結果。 分組值的順序是由他們出現在 collection(集合) 中的順序確定的。每個鍵對應的值負責生成 key 的元素組成的數組。iteratee 調用 1 個參數: (value)。

        如:var users = [
           { 'user': 'barney', 'age': 36, 'active': true },
           { 'user': 'fred',   'age': 40, 'active': false }
         ];
         _.groupBy(users, 'user');
         // => {"barney":[{"user":"barney","age":36,"active":true}],"fred":[{"user":"fred","age":40,"active":false}]}
         
         
    • _.includes(collection, value, [fromIndex=0])
      檢查 value(值) 是否在 collection(集合) 中。如果 collection(集合)是一個字符串,那麼檢查 value(值,子字符串) 是否在字符串中, 否則使用 SameValueZero 做等值比較。 如果指定 fromIndex 是負數,那麼從 collection(集合) 的結尾開始檢索。

        如:_.includes([1, 2, 3], 1);
            // => true
             
            _.includes([1, 2, 3], 1, 2);
            // => false
             
            _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
            // => true
             
            _.includes('pebbles', 'eb');
            // => true
            
            
    • _.orderBy(collection, [iteratees=[_.identity]], [orders])
      此方法類似於_.sortBy,除了它允許指定 iteratee(迭代函數)結果如何排序。 如果沒指定 orders(排序),所有值以升序排序。 否則,指定爲"desc" 降序,或者指定爲 "asc" 升序,排序對應值。

        如:var users = [
          { 'user': 'fred',   'age': 48 },
          { 'user': 'barney', 'age': 34 },
          { 'user': 'fred',   'age': 40 },
          { 'user': 'barney', 'age': 36 }
        ];
         
        // 以 `user` 升序排序 再  `age` 以降序排序。
        _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
        // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
        
    • _.sortBy(collection, [iteratees=[_.identity]])
      創建一個元素數組。 以 iteratee 處理的結果升序排序。 這個方法執行穩定排序,也就是說相同元素會保持原始排序。 iteratees 調用1個參數: (value)。

        如:var users = [
          { 'user': 'fred',   'age': 48 },
          { 'user': 'barney', 'age': 36 },
          { 'user': 'fred',   'age': 40 },
          { 'user': 'barney', 'age': 34 }
        ];
         
        _.sortBy(users, function(o) { return o.user; });
        // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
         
        _.sortBy(users, ['user', 'age']);
        // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
         
        _.sortBy(users, 'user', function(o) {
          return Math.floor(o.age / 10);
        });
        // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
        
        
    • _.debounce(func, [wait=0], [options={}])
      創建一個 debounced(防抖動)函數,該函數會從上一次被調用後,延遲 wait 毫秒後調用 func 方法。 debounced(防抖動)函數提供一個 cancel 方法取消延遲的函數調用以及 flush 方法立即調用。 可以提供一個 options(選項) 對象決定如何調用 func 方法,options.leading 與|或 options.trailing 決定延遲前後如何觸發(愚人碼頭注:是 先調用後等待 還是 先等待後調用)。 func 調用時會傳入最後一次提供給 debounced(防抖動)函數 的參數。 後續調用的 debounced(防抖動)函數返回是最後一次 func 調用的結果。

      注意: 如果 leading 和 trailing 選項爲 true, 則 func 允許 trailing 方式調用的條件爲: 在 wait 期間多次調用防抖方法。

      如果 wait 爲 0 並且 leading 爲 false, func調用將被推遲到下一個點,類似setTimeout爲0的超時。

        如:// 避免窗口在變動時出現昂貴的計算開銷。
        jQuery(window).on('resize', _.debounce(calculateLayout, 150));
         
        // 當點擊時 `sendMail` 隨後就被調用。
        jQuery(element).on('click', _.debounce(sendMail, 300, {
          'leading': true,
          'trailing': false
        }));
         
        // 確保 `batchLog` 調用1次之後,1秒內會被觸發。
        var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
        var source = new EventSource('/stream');
        jQuery(source).on('message', debounced);
         
        // 取消一個 trailing 的防抖動調用
        jQuery(window).on('popstate', debounced.cancel);
      
      
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章