拾遗

最后,我们介绍一些集合部分遗漏的 API。

_.max

_.max(coll, iteratee):根据 iteratee 声明的大小关系,获得 coll 最大元素。

源码

_.max = function (obj, iteratee, context) {
    // 默认返回-Infinity
    var result = -Infinity, lastComputed = -Infinity,
        value, computed;
    if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
        // 如果没有传递iteratee, 则按值进行比较
        obj = isArrayLike(obj) ? obj : _.values(obj);
        for (var i = 0, length = obj.length; i < length; i++) {
            value = obj[i];
            if (value != null && value > result) {
                result = value;
            }
        }
    } else {
        // 否则, 以iteratee为最大值依据, 每次传入当前迭代值给iteratee, 算出最大值
        iteratee = cb(iteratee, context);
        _.each(obj, function (v, index, list) {
            computed = iteratee(v, index, list);
            if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
                result = v;
                lastComputed = computed;
            }
        });
    }
    return result;
};

用例

var students = [
  {name: 'wxj', age: 18},
  {name: 'john', age: 14},
  {name: 'bob', age: 23}
];

_.max(students, 'age');
// {name: 'bob', age:23}

_.min

_.min(coll, iteratee):根据 iteratee 声明的大小关系,获得 coll 最小元素。

源码

_.min = function (obj, iteratee, context) {
    var result = Infinity, lastComputed = Infinity,
        value, computed;
    if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) {
        obj = isArrayLike(obj) ? obj : _.values(obj);
        for (var i = 0, length = obj.length; i < length; i++) {
            value = obj[i];
            if (value != null && value < result) {
                result = value;
            }
        }
    } else {
        iteratee = cb(iteratee, context);
        _.each(obj, function (v, index, list) {
            computed = iteratee(v, index, list);
            if (computed < lastComputed || computed === Infinity && result === Infinity) {
                result = v;
                lastComputed = computed;
            }
        });
    }
    return result;
};

用例

var students = [
  {name: 'wxj', age: 18},
  {name: 'john', age: 14},
  {name: 'bob', age: 23}
];

_.min(students, 'age');
// {name: 'john', age:14}

_.invokde

_.invoke(coll, method):迭代 coll,对每个元素调用其成员方法 method

源码

_.invoke = restArgs(function (obj, method, args) {
    // 通过闭包避免每次重复调用_.isFunction(method)
    var isFunc = _.isFunction(method);
    return _.map(obj, function (value) {
        var func = isFunc ? method : value[method];
        // 如果对象上不存在方法, 则返回null
        return func == null ? func : func.apply(value, args);
    });
});

用例

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
// => [[1, 5, 7], [1, 2, 3]]

results matching ""

    No results matching ""