函數式編程 lodash 經常使用api

一、forEachhtml

複製代碼
_.forEach({
                'a': 1,
                'b': 2
            }, function(value, key) {
                console.log(key);
            });
            _.forEach([3,4], function(value) {
                console.log(value);
            });
複製代碼

二、filterjquery

複製代碼
var users = [{
                    'user': 'barney',
                    'age': 36,
                    'active': true
                },
                {
                    'user': 'fred',
                    'age': 40,
                    'active': false
                }
            ];
            var usersNew = _.filter(users, function(o) {
                return !o.active;
            })
            console.log(usersNew)
            var usersNew2 = _.filter(users, {'active': true })
            console.log(usersNew2)
            var usersNew3 = _.filter(users, ['active', false])
            console.log(usersNew3)
            //active 值爲true
            var usersNew4 = _.filter(users, 'active')
            console.log(usersNew4)
複製代碼

三、random數組

_.random([min=0], [max=1], [floating])

產生一個包括 min 與 max 之間的數。 若是隻提供一個參數返回一個0到提供數之間的數。 若是 floating 設爲 true,或者 min 或 max 是浮點數,結果返回浮點數。 dom

四、深拷貝_.cloneDeepide

五、擴展對象_.assign函數

六、去掉對象屬性_.omitspa

七、從某個對象中選擇部分屬性組成新的對象  _.pickcode

八、排序_.orderByhtm

 

複製代碼
var users = [{
                    'user': 'fred',
                    'age': 48
                },
                {
                    'user': 'barney',
                    'age': 34
                },
                {
                    'user': 'fred',
                    'age': 42
                },
                {
                    'user': 'barney',
                    'age': 36
                }
            ];

            console.log(_.orderBy(users, ['age'], ['desc']))
複製代碼

 9 、函數執行N次對象

_.times(n, [iteratee=_.identity])

調用 iteratee N 次,每次調用返回的結果存入到數組中。 iteratee 會傳入1個參數:(index)。

 

console.log(_.times(3, String))

十、等差數組

console.log(_.range(0, 20, 5))
            // [0, 5, 10, 15]

十一、isEmpty

 檢查 value 是否爲空。 判斷的依據是除非是有枚舉屬性的對象,length 大於 0 的 arguments object, array, string 或類jquery選擇器。

 12.take

 

_.take(array, [n=1])

 

從數組的起始元素開始提取 N 個元素。(如可實現分頁)

複製代碼
_.take([1, 2, 3]);
// => [1]

_.take([1, 2, 3], 2);
// => [1, 2]

_.take([1, 2, 3], 5);
// => [1, 2, 3]

_.take([1, 2, 3], 0);
// => []
複製代碼

 1三、

_.reject(collection, [predicate=_.identity])

反向版 _.filter,這個方法返回 predicate 檢查爲非真值的元素。

 1四、_.assign

複製代碼
var a = {
                    a: 1
                },
                b = {
                    b: 2
                },
                c = {
                    c: 3
                };
            var d = {};
            var d = _.assign(d, a, b, c);

            console.log(a)
            console.log(b)
            console.log(c)
            console.log(d)
複製代碼
相關文章
相關標籤/搜索