lodash(二)對象+循環遍歷+排序


  • 前言:

lodash(一)中只是研究了array中的多種方法,接下來就是經常用到的循環遍歷問題

  • 過程:

1._.forEach(collection, [iteratee=_.identity], [thisArg])  遍歷

    _.forEach([22,33,11,55],function (value) {//若一個參數,返回的便是其value值
      console.log(value);//22 33 11 55
    });
    _.forEach([22,33,11,55],function (value,index) {//這里規定的就是第一個參數返回的是value值,第二個參數是下標index
      console.log(value);
    });

2._.sortBy(collection, [iteratee=_.identity], [thisArg])   排序匿名函數+字符串

    var arr = [
        {name: 'bb',age:23},
        {name: 'aa',age:22}
    ];

    var arrSortResult = _.sortBy(arr, function(item){
        return item.name;
    });
    _.forEach(arrSortResult, function(item){
        console.log(item.name); //aa bb
    });
    var strSortResult = _.sortBy('cda').join('');//join()方法 方法用於把數組中的所有元素放入一個字符串。元素是通過指定的分隔符進行分隔的。
     console.log(strSortResult);//acd

3._.sortedIndex(array, value, [iteratee=_.identity], [thisArg]) 

         參數:array (Array): 需要檢查的數組    value (*): 插入的判斷參數    [iteratee=_.identity] (Function|Object|string): 遍歷方法   [thisArg] (*): iteratee的綁定值

    var collection = ['a', 'b', 'c', 'd', 'f'];
    console.log('before: ' + collection.join(' '));//before: a b c d f
    var toBeInserted = 'e';
    var sortedIndex = _.sortedIndex(collection, toBeInserted);
    console.log("This is sortedIndex:"+sortedIndex);//This is sortedIndex:4
    collection.splice(sortedIndex, 0, toBeInserted);
    console.log('after:' + collection.join(' '));//after:a b c d e f
  • 后言:

只是簡單了解了一下關於lodash部分,卻發現使用它可以快速解決自己之前遇到的很多問題,希望以后工作中可以應用自如。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM