• lodash学习资料


    二、Lodash

    Lodash是一个具有一致接口、模块化、高性能等特性的 JavaScript 工具库。它内部封装了诸多对字符串、数组、对象等常见数据类型的处理函数,其中部分是目前 ECMAScript 尚未制定的规范,但同时被业界所认可的辅助函数。目前每天使用 npm 安装 Lodash 的数量在百万级以上,这在一定程度上证明了其代码的健壮性,值得我们在项目中一试。

    官网:https://lodash.com/

    中文文档:http://www.css88.com/doc/lodash/

    英文帮助:https://lodash.com/docs/

    GitHub:https://github.com/lodash/

     

    2.1、下载

    CDN引用地址:https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js

     

    2.2、安装

    浏览器:

    <script src="lodash.js"></script>
    //或CDN
    <script scr="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>

    用npm:

    $ npm i -g npm
    $ npm i --save lodash

    Nodejs:

     
    // Load the full build.
    var _ = require('lodash');
    // Load the core build.
    var _ = require('lodash/core');
    // Load the FP build for immutable auto-curried iteratee-first data-last methods.
    var fp = require('lodash/fp');
    
    // Load method categories.
    var array = require('lodash/array');
    var object = require('lodash/fp/object');
    
    // Cherry-pick methods for smaller browserify/rollup/webpack bundles.
    var at = require('lodash/at');
    var curryN = require('lodash/fp/curryN');
     
     

    2.3、模块组成

    Lodash 提供的辅助函数主要分为以下几类,函数列表和用法实例请查看 Lodash 的官方文档:

    Array,适用于数组类型,比如填充数据、查找元素、数组分片等操作

    Collection,适用于数组和对象类型,部分适用于字符串,比如分组、查找、过滤等操作

    Function,适用于函数类型,比如节流、延迟、缓存、设置钩子等操作

    Lang,普遍适用于各种类型,常用于执行类型判断和类型转换

    Math,适用于数值类型,常用于执行数学运算

    Number,适用于生成随机数,比较数值与数值区间的关系

    Object,适用于对象类型,常用于对象的创建、扩展、类型转换、检索、集合等操作

    Seq,常用于创建链式调用,提高执行性能(惰性计算)

    String,适用于字符串类型

    lodash/fp 模块提供了更接近函数式编程的开发方式,其内部的函数经过包装,具有immutable、auto-curried、iteratee-first、data-last(官方介绍)等特点

     

    2.4、Lodash快速入门实例

     

    2.4.1. N 次循环

     
    // 1. Basic for loop.
    for(var i = 0; i < 5; i++) {
    // ...
    }
    
    // 2. Using Array's join and split methods
    Array.apply(null, Array(5)).forEach(function(){
    // ...
    });
    
    // Lodash
    _.times(5, function(){
    // ...
    });
     

    for 语句是执行循环的不二选择,Array.apply 也可以模拟循环,但在上面代码的使用场景下,_.times() 的解决方式更加简洁和易于理解。

    示例:

     
    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
    
        <body>
            <div id="vm">
    
            </div>
            <script src="../js/vue.js" type="text/javascript" charset="utf-8"></script>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var vm = new Vue({
                    el: "#vm",
                    data: {
                        msg: ""
                    },
                    methods: {
    
                    }
                });
    
                var log = function(str) {
                    console.log(str);
                }
    
                log(_.times(5));
                log(_.times(5, String));
                log(_.times(5, _.constant(0)));
                log(_.times(5, _.constant(true)));
                var a5=_.times(5, function(v) {
                    return v+10;
                })
                log(a5);
            </script>
        </body>
    
    </html>
     

    结果:

     

    2.4.2. 深层查找属性值

     
    // Fetch the name of the first pet from each owner
    var ownerArr = [{
    "owner": "Colin",
    "pets": [{"name":"dog1"}, {"name": "dog2"}]
    }, {
    "owner": "John",
    "pets": [{"name":"dog3"}, {"name": "dog4"}]
    }];
    
    // Array's map method.
    ownerArr.map(function(owner){
      return owner.pets[0].name;
    });
    
    // Lodash
    _.map(ownerArr, 'pets[0].name');
     

    _.map 方法是对原生 map 方法的改进,其中使用 pets[0].name 字符串对嵌套数据取值的方式简化了很多冗余的代码,非常类似使用 jQuery 选择 DOM 节点 ul > li > a,对于前端开发者来说有种久违的亲切感。

    示例:

     
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
        <body>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var log = function(str) {
                    if(typeof str == "object")
                    {
                        console.log(JSON.stringify(str));
                    }
                    console.log(str);
                }
    
                var arr = [{
                    "owner": "Colin",
                    "pets": [{
                        "name": "dog1"
                    }, {
                        "name": "dog2"
                    }]
                }, {
                    "owner": "John",
                    "pets": [{
                        "name": "dog3"
                    }, {
                        "name": "dog4"
                    }]
                }];
                
                log(_.map(arr,"pets"));
                log(_.map(arr,"owner"));
                log(_.map(arr,"pets[1].name"));
                log(_.map(arr,o=>o.pets[1].name+":)"));
            </script>
        </body>
    
    </html>
     

    结果:

     

    2.4.3. 个性化数组

     
    // Array's map method.
    Array.apply(null, Array(6)).map(function(item, index){
    return "ball_" + index;
    });
    
    // Lodash
    _.times(6, _.uniqueId.bind(null, 'ball_'));
    
    // Lodash
    _.times(6, _.partial(_.uniqueId, 'ball_'));
    // eg. [ball_0, ball_1, ball_2, ball_3, ball_4, ball_5]
     

    在上面的代码中,我们要创建一个初始值不同、长度为 6 的数组,其中 _.uniqueId 方法用于生成独一无二的标识符(递增的数字,在程序运行期间保持独一无二),_partial 方法是对 bind 的封装。

    示例:

     
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
        <body>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var log = function(str) {
                    if(typeof str == "object")
                    {
                        console.log(JSON.stringify(str));
                    }
                    console.log(str);
                }
                //产生唯一编号
                log(_.uniqueId());
                log(_.uniqueId("gdnf_"));
                
                //封装函数
                function greet(greeting,name){
                    return greeting +" " +name;
                }
                log(greet("hello","tom"));
                
                var sayhello=_.partial(greet,'hello');
                var sayhi=_.partial(greet,'hi');
                
                log(sayhello('mark'));
                log(sayhi('rose'));
                
                //综合
                var array=_.times(5,_.partial(_.uniqueId,'ball_'));
                log(array);
            </script>
        </body>
    
    </html>
     

    结果:

     

    2.4.4. 深拷贝

     
    var objA = {
    "name": "colin"
    }
    
    // Normal method? Too long. See Stackoverflow for solution:
    // http://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript
    
    // Lodash
    var objB = _.cloneDeep(objA);
    objB === objA // false
     

    JavaScript 没有直接提供深拷贝的函数,但我们可以用其他函数来模拟,比如 JSON.parse(JSON.stringify(objectToClone)),但这种方法要求对象中的属性值不能是函数。Lodash 中的 _.cloneDeep 函数封装了深拷贝的逻辑,用起来更加简洁。

    示例:

     
    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
    
        <body>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var log = function(str) {
                    if(typeof str == "object") {
                        console.log(JSON.stringify(str));
                    }
                    console.log(str);
                }
                var obj0={address:"中国珠海"};
                var obj1 = {
                    id: 1,
                    name: "rose",
                    position:obj0
                };
                log("引用");
                //引用
                var obj2=obj1;
                log(obj2==obj1);
                log("浅拷贝");
                //浅拷贝
                var obj3=_.clone(obj1);
                log(obj3==obj1);
                log(obj3===obj1);
                log(obj3.position===obj1.position);
                log("深拷贝");
                //深拷贝
                var obj4=_.cloneDeep(obj1);
                log(obj4==obj1);
                log(obj4===obj1);
                log(obj4.position===obj1.position);
            </script>
        </body>
    
    </html>
     

    结果:

     

    2.4.5. 随机数

     
    // Naive utility method
    function getRandomNumber(min, max){
    return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    getRandomNumber(15, 20);
    
    // Lodash
    _.random(15, 20);
     

    Lodash 的随机数生成函数更贴近实际开发,ECMAScript 的随机数生成函数是底层必备的接口,两者都不可或缺。此外,使用 _.random(15, 20, true) 还可以在 15 到 20 之间生成随机的浮点数。

    示例:

     
    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
    
        <body>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var log = function(str) {
                    if(typeof str == "object") {
                        console.log(JSON.stringify(str));
                    }
                    console.log(str);
                }
                var obj0={address:"中国珠海"};
                var obj1 = {
                    id: 1,
                    name: "rose",
                    position:obj0
                };
                
                var arr=_.times(10,function(){
                    return _.random(1,100);
                });
                log(arr);
            </script>
        </body>
    
    </html>
     

    结果:

     

    2.4.6. 对象扩展

     
    // Adding extend function to Object.prototype
    Object.prototype.extend = function(obj) {
    for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
    this[i] = obj[i];
    }
    }
    };
    
    var objA = {"name": "colin", "car": "suzuki"};
    var objB = {"name": "james", "age": 17};
    
    objA.extend(objB);
    objA; // {"name": "james", "age": 17, "car": "suzuki"};
    
    // Lodash
    _.assign(objA, objB);
     

    _.assign 是浅拷贝,和 ES6 新增的 Ojbect.assign 函数功能一致(建议优先使用 Object.assign)。

    示例:

     
    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
    
        <body>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var log = function(str) {
                    if(typeof str == "object") {
                        console.log(JSON.stringify(str));
                    }
                    console.log(str);
                }
                var obj0 = {
                    address: "中国珠海"
                };
                var obj1 = {
                    id: 1,
                    name: "rose",
                    position: obj0
                };
    
                var x = {
                    a: 1,
                    b: 2,
                    c: 3
                };
                var y = {
                    b: 5,
                    c: 6,
                    d: 7
                };
                //用y扩展x
                _.assign(x,y);
                log(x);  //x被修改了
                log(y);
            </script>
        </body>
    </html>
     

    结果:

     

    2.4.7. 筛选属性

     
    // Naive method: Remove an array of keys from object
    Object.prototype.remove = function(arr) {
    var that = this;
    arr.forEach(function(key){
    delete(that[key]);
    });
    };
    
    var objA = {"name": "colin", "car": "suzuki", "age": 17};
    
    objA.remove(['car', 'age']);
    objA; // {"name": "colin"}
    
    // Lodash
    objA = _.omit(objA, ['car', 'age']);
    // => {"name": "colin"}
    objA = _.omit(objA, 'car');
    // => {"name": "colin", "age": 17};
    objA = _.omit(objA, _.isNumber);
    // => {"name": "colin"};
     

    大多数情况下,Lodash 所提供的辅助函数都会比原生的函数更贴近开发需求。在上面的代码中,开发者可以使用数组、字符串以及函数的方式筛选对象的属性,并且最终会返回一个新的对象,中间执行筛选时不会对旧对象产生影响。

     
    // Naive method: Returning a new object with selected properties
    Object.prototype.pick = function(arr) {
    var _this = this;
    var obj = {};
    arr.forEach(function(key){
    obj[key] = _this[key];
    });
    
    return obj;
    };
    
    var objA = {"name": "colin", "car": "suzuki", "age": 17};
    
    var objB = objA.pick(['car', 'age']);
    // {"car": "suzuki", "age": 17}
    
    // Lodash
    var objB = _.pick(objA, ['car', 'age']);
    // {"car": "suzuki", "age": 17}
     

    _.pick 是 _.omit 的相反操作,用于从其他对象中挑选属性生成新的对象。

    示例:

     
    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
    
        <body>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var log = function(str) {
                    if(typeof str == "object") {
                        console.log(JSON.stringify(str));
                    }
                    console.log(str);
                }
                var obj0 = {
                    address: "中国珠海"
                };
                var obj1 = {
                    id: 1,
                    name: "rose",
                    position: obj0
                };
    
                var student = {
                    name: "张三",
                    age: 18,
                    address: "中国香港"
                };
    
                //删除属性地址,未修改原数组
                var obj1 = _.omit(student, "address");
                log(obj1);
                
                var obj2 = _.omit(student, ['age','name']);
                log(obj2);
            </script>
        </body>
    
    </html>
     

    结果:

     

    2.4.8. 随机元素

     
    var luckyDraw = ["Colin", "John", "James", "Lily", "Mary"];
    
    function pickRandomPerson(luckyDraw){
    var index = Math.floor(Math.random() * (luckyDraw.length -1));
    return luckyDraw[index];
    }
    
    pickRandomPerson(luckyDraw); // John
    
    // Lodash
    _.sample(luckyDraw); // Colin
    
    // Lodash - Getting 2 random item
    _.sample(luckyDraw, 2); // ['John','Lily']
     

    _.sample 支持随机挑选多个元素并返回新的数组。

    示例:

     
    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title>Lodash</title>
        </head>
    
        <body>
            <script src="../js/lodash/lodash.min.js" type="text/javascript" charset="utf-8"></script>
            <script type="text/javascript">
                var log = function(str) {
                    if(typeof str == "object") {
                        console.log(JSON.stringify(str));
                    }
                    console.log(str);
                }
                var luckyDraw = ["Colin", "John", "James", "Lily", "Mary"];
                
                //随机获得一个
                log(_.sample(luckyDraw));
                //随机获得多个
                log(_.sampleSize(luckyDraw,2));
            </script>
        </body>
    
    </html>
     

    结果:

     

    2.4.9. 针对 JSON.parse 的错误处理

     
    // Using try-catch to handle the JSON.parse error
    function parse(str){
    try {
    return JSON.parse(str);
    }
    
    catch(e) {
    return false;
    }
    }
    
    // With Lodash
    function parseLodash(str){
    return _.attempt(JSON.parse.bind(null, str));
    }
    
    parse('a');
    // => false
    parseLodash('a');
    // => Return an error object
    
    parse('{"name": "colin"}');
    // => Return {"name": "colin"}
    parseLodash('{"name": "colin"}');
    // => Return {"name": "colin"}
     

    如果你在使用 JSON.parse 时没有预置错误处理,那么它很有可能会成为一个定时炸弹,我们不应该默认接收的 JSON 对象都是有效的。try-catch 是最常见的错误处理方式,如果项目中 Lodash,那么可以使用 _.attmpt 替代 try-catch 的方式,当解析 JSON 出错时,该方法会返回一个 Error 对象。

    随着 ES6 的普及,Lodash 的功能或多或少会被原生功能所替代,所以使用时还需要进一步甄别,建议优先使用原生函数。

     

    2.5、更多功能

    1) _.map(collection, [iteratee=_.identity], [thisArg])

     作用:创建一个经过 iteratee 处理的集合中每一个元素的结果数组. iteratee 会传入3个参数:(value, index|key, collection). 

     别名(Aliases):_.collect

     参数1): 需要遍历的集合,可以是数组,对象或者字符串.

     参数2): 迭代器,可以是函数,对象或者字符串.

     参数3): 迭代器中this所绑定的对象.

     返回值(Array): 映射后的新数组.

     示例:

     
     1 function timesThree(n) {
     2   return n * 3;
     3 }
     4 
     5 _.map([1, 2], timesThree);
     6 // => [3, 6]
     7 
     8 _.map({ 'a': 1, 'b': 2 }, timesThree);
     9 // => [3, 6] (iteration order is not guaranteed)
    10 
    11 var users = [
    12   { 'user': 'barney' },
    13   { 'user': 'fred' }
    14 ];
    15 
    16 // using the `_.property` callback shorthand
    17 _.map(users, 'user');
    18 // => ['barney', 'fred']
     

    2) _.chunk(array, [size=1])

     作用:将 array 拆分成多个 size 长度的块,把这些块组成一个新数组。 如果 array 无法被分割成全部等长的块,那么最后剩余的元素将组成一个块.

     参数1): 需要被处理的数组.

     参数2): 每个块的长度.

     返回值(Array): 返回一个包含拆分块数组的新数组(相当于一个二维数组).

     示例:

     
    1 _.chunk(['a', 'b', 'c', 'd'], 2);
    2 // => [['a', 'b'], ['c', 'd']]
    3 
    4 _.chunk(['a', 'b', 'c', 'd'], 3);
    5 // => [['a', 'b', 'c'], ['d']]
     

    3) _.compact(array)

     作用:创建一个新数组并包含原数组中所有的非假值元素。例如 falsenull、 0""undefined 和 NaN 都是“假值”.

     参数: 需要被过滤的数组.

     返回值(Array): 过滤假值后的数组.

     示例:

    1 _.compact([0, 1, false, 2, '', 3]);
    2 // => [1, 2, 3]

    4) _.difference(array, [values])

     作用:创建一个差异化后的数组,不包括使用 SameValueZero 方法提供的数组.

     参数1): 需要处理的数组.

     参数2): 数组需要排除掉的值.

     返回值(Array): 过滤后的数组.

     示例:

    1 _.difference([1, 2, 3], [4, 2]);
    2 // => [1, 3]
    3 _.difference([1, '2', 3], [4, 2]);
    4 // => [1, "2", 3]

    5) _.drop(array, [n=1])

     作用:将 array 中的前 n 个元素去掉,然后返回剩余的部分.

     参数1): 被操作的数组.

     参数2): 去掉的元素个数.

     返回值(Array): 数组的剩余部分.

     示例:

     
     1 _.drop([1, 2, 3]);
     2 // => [2, 3] 默认是1开始的
     3 
     4 _.drop([1, 2, 3], 2);
     5 // => [3]
     6 
     7 _.drop([1, 2, 3], 5);
     8 // => []
     9 
    10 _.drop([1, 2, 3], 0);
    11 // => [1, 2, 3]
     

    6)_.dropRight(array, [n=1])

     作用:将 array 尾部的 n 个元素去除,并返回剩余的部分.

     参数1): 需要被处理的数组.

     参数2): 去掉的元素个数.

     返回值(Array): 数组的剩余部分.

     示例:

     
     1 _.dropRight([1, 2, 3]);
     2 // => [1, 2]
     3 
     4 _.dropRight([1, 2, 3], 2);
     5 // => [1]
     6 
     7 _.dropRight([1, 2, 3], 5);
     8 // => []
     9 
    10 _.dropRight([1, 2, 3], 0);
    11 // => [1, 2, 3]
     

    7)_.dropRightWhile(array, [predicate=_.identity], [thisArg])

     作用:从尾端查询(右数)数组 array ,第一个不满足predicate 条件的元素开始截取数组.

     参数1): 需要查询的数组.

     参数2): 迭代器,可以是函数,对象或者字符串.

     参数3): 对应 predicate 属性的值.

     返回值(Array): 截取元素后的数组.

     示例:

     
     1 _.dropRightWhile([1, 2, 3], function(n) {
     2   return n > 1;
     3 });
     4 // => [1]
     5 
     6 var users = [
     7   { 'user': 'barney',  'active': true },
     8   { 'user': 'fred',    'active': false },
     9   { 'user': 'pebbles', 'active': false }
    10 ];
    11 
    12 // using the `_.matches` callback shorthand
    13 _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
    14 // => ['barney', 'fred']
    15 
    16 // using the `_.matchesProperty` callback shorthand
    17 _.pluck(_.dropRightWhile(users, 'active', false), 'user');
    18 // => ['barney']
    19 
    20 // using the `_.property` callback shorthand
    21 _.pluck(_.dropRightWhile(users, 'active'), 'user');
    22 // => ['barney', 'fred', 'pebbles']
     

     8)_.pluck(collection, path)

     作用:抽取集合中path所指定的路径的属性值.

     参数1): 需要抽取的数组.

     参数2): 需要抽取的属性所对应的路径.

     返回值(Array): 抽取的属性值所组成的数组.

     示例:

     
     1 var users = [
     2   { 'user': 'barney', 'age': 36 },
     3   { 'user': 'fred',   'age': 40 }
     4 ];
     5 
     6 _.pluck(users, 'user');
     7 // => ['barney', 'fred']
     8 
     9 var userIndex = _.indexBy(users, 'user');
    10 _.pluck(userIndex, 'age');
    11 // => [36, 40] (iteration order is not guaranteed)
     

    9)_.fill(array, value, [start=0], [end=array.length])

     作用:使用 value 值来填充(也就是替换) array,从start位置开始, 到end位置结束(但不包含end位置).

     参数1): 需要填充的数组.

     参数2): 填充 array 元素的值.

     参数3): 起始位置(包含).

     参数4): 结束位置(不含).

     返回值(Array): 填充后的数组.

     示例:

     
     1 var array = [1, 2, 3];
     2 
     3 _.fill(array, 'a');
     4 console.log(array);
     5 // => ['a', 'a', 'a']
     6 
     7 _.fill(Array(3), 2);
     8 // => [2, 2, 2]
     9 
    10 _.fill([4, 6, 8], '*', 1, 2);
    11 // => [4, '*', 8]
     

    10)_.findIndex(array, [predicate=_.identity], [thisArg])

     作用:该方法类似 _.find,区别是该方法返回的是符合 predicate条件的第一个元素的索引,而不是返回元素本身. 

     参数1): 需要搜索的数组.

     参数2): 迭代器,可以是函数,对象或者字符串.

     参数3): 对应 predicate 属性的值.

     返回值(Number): 符合查询条件的元素的索引值, 未找到则返回 -1.

     示例:

     
     1 var users = [
     2   { 'user': 'barney',  'active': false },
     3   { 'user': 'fred',    'active': false },
     4   { 'user': 'pebbles', 'active': true }
     5 ];
     6 
     7 _.findIndex(users, function(chr) {
     8   return chr.user == 'barney';
     9 });
    10 // => 0
    11 
    12 // using the `_.matches` callback shorthand
    13 _.findIndex(users, { 'user': 'fred', 'active': false });
    14 // => 1
    15 
    16 // using the `_.matchesProperty` callback shorthand
    17 _.findIndex(users, 'active', false);
    18 // => 0
    19 
    20 // using the `_.property` callback shorthand
    21 _.findIndex(users, 'active');
    22 // => 2
     

    11)_.find(collection, [predicate=_.identity], [thisArg])

     作用:遍历集合中的元素,返回最先经 predicate 检查为真值的元素. predicate 会传入3个元素:(value, index|key, collection).

     参数1): 要检索的集合,可以是数组,对象或者字符串.

     参数2): 迭代器,可以是函数,对象或者字符串.

     参数3): 迭代器中this所绑定的对象.

     返回值: 匹配元素,否则返回 undefined.

     示例:

     
     1 var users = [
     2   { 'user': 'barney',  'age': 36, 'active': true },
     3   { 'user': 'fred',    'age': 40, 'active': false },
     4   { 'user': 'pebbles', 'age': 1,  'active': true }
     5 ];
     6 
     7 _.find(users, function(o) { return o.age < 40; });
     8 // =>  'barney'
     9 
    10 // 使用了 `_.matches` 的回调结果
    11 _.find(users, { 'age': 1, 'active': true });
    12 // =>  'pebbles'
    13 
    14 // 使用了 `_.matchesProperty` 的回调结果
    15 _.find(users, ['active', false]);
    16 // =>  'fred'
    17 
    18 // 使用了 `_.property` 的回调结果
    19 _.find(users, 'active');
    20 // =>  'barney'
     

     12)_.forEach(collection, [iteratee=_.identity], [thisArg])

     作用:调用 iteratee 遍历集合中的元素, iteratee 会传入3个参数:(value, index|key, collection)。 如果显式的返回 false ,iteratee 会提前退出.

     参数1): 需要遍历的集合,可以是数组,对象或者字符串.

     参数2): 迭代器,只能是函数.

     参数3): 迭代器中this所绑定的对象.

     返回值: 遍历后的集合.

     示例:

     
    1 _([1, 2]).forEach(function(value) {
    2   console.log(value);
    3 });
    4 // => 输出 `1` 和 `2`
    5 
    6 _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
    7   console.log(key);
    8 });
    9 // => 输出 'a' 和 'b' (不保证遍历的顺序)
     

    13)_.reduce(collection, [iteratee=_.identity], [accumulator], [thisArg])

     作用:通过 iteratee 遍历集合中的每个元素. 每次返回的值会作为下一次 iteratee 使用。如果没有提供accumulator,则集合中的第一个元素作为 accumulator. iteratee 会传入4个参数:(accumulator, value, index|key, collection).

     参数1): 需要遍历的集合,可以是数组,对象或者字符串.

     参数2): 迭代器,只能是函数.

     参数3): 累加器的初始化值.

     参数4): 迭代器中this所绑定的对象.

     返回值: 累加后的值.

     示例:

     
     1 _.reduce([1, 2], function(total, n) {
     2   return total + n;
     3 });
     4 // => 3
     5 
     6 _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
     7   result[key] = n * 3;
     8   return result;
     9 }, {});
    10 // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
     

    14)_.some(collection, [predicate=_.identity], [thisArg])

     作用:通过 predicate 检查集合中的元素是否存在任意真值的元素,只要 predicate 返回一次真值,遍历就停止,并返回 true. predicate 会传入3个参数:(value, index|key, collection).

     参数1): 需要遍历的集合,可以是数组,对象或者字符串.

     参数2): 迭代器,可以是函数,对象或字符串.

     参数3): 迭代器中this所绑定的对象.

     返回值: 如果任意元素经 predicate 检查都为真值,则返回true,否则返回 false.

     示例:

     
     1 _.some([null, 0, 'yes', false], Boolean);
     2 // => true
     3 
     4 var users = [
     5   { 'user': 'barney', 'active': true },
     6   { 'user': 'fred',   'active': false }
     7 ];
     8 
     9 // using the `_.matches` callback shorthand
    10 _.some(users, { 'user': 'barney', 'active': false });
    11 // => false
    12 
    13 // using the `_.matchesProperty` callback shorthand
    14 _.some(users, 'active', false);
    15 // => true
    16 
    17 // using the `_.property` callback shorthand
    18 _.some(users, 'active');
    19 // => true
     

    15)_.chain(value)

     作用:创建一个包含 value 的 lodash 对象以开启内置的方法链.方法链对返回数组、集合或函数的方法产生作用,并且方法可以被链式调用.

     参数: 需要被包裹成lodash对象的值.

     返回值: 新的lodash对象的实例.

     示例:

     
     1 var users = [
     2   { 'user': 'barney',  'age': 36 },
     3   { 'user': 'fred',    'age': 40 },
     4   { 'user': 'pebbles', 'age': 1 }
     5 ];
     6 
     7 var youngest = _.chain(users)
     8   .sortBy('age')
     9   .map(function(chr) {
    10     return chr.user + ' is ' + chr.age;
    11   })
    12   .first()
    13   .value();
    14 // => 'pebbles is 1'
     
  • 相关阅读:
    js 中常用的方法
    js中this的四种调用模式
    JS面向对象的几种写法
    js 中的算法题,那些经常看到的
    web页面的回流,认识与避免
    js中的预加载与懒加载(延迟加载)
    Web安全测试学习笔记-DVWA-存储型XSS
    Web安全测试学习笔记-DVWA-图片上传
    Web安全测试学习笔记-DVWA-盲注(使用sqlmap)
    Web安全测试学习笔记-DVWA-SQL注入-1
  • 原文地址:https://www.cnblogs.com/xiongshuangping/p/10100900.html
Copyright © 2020-2023  润新知