lodash源码解读util第一部分

栏目: JavaScript · 发布时间: 7年前

内容简介:1. _.attempt(func, [args])执行方法, 返回结果或者错误, 搭配_.isError使用源码
  • 源码版本4.17.4

1. _.attempt(func, [args])

执行方法, 返回结果或者错误, 搭配_.isError使用

源码

function attempt(func, ...args) {
  try {
    return func.apply(undefined, args)
  } catch (e) {
    return isError(e) ? e : new Error(e)
  }
}

调用利用函数的apply + try catch

示例

// Avoid throwing errors for invalid selectors.
var elements = _.attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');
 
if (_.isError(elements)) {
  elements = [];
}

2. _.cond(pairs)

创建一个迭代对的函数.

pairs本身是数组, 每一项也是包含两个函数的数组.

当执行迭代函数时, 如果第一个函数返回true, 就执行改项的第二个函数,反之, 执行下一项.

function cond(pairs) {
  const length = pairs == null ? 0 : pairs.length

  pairs = !length ? [] : map(pairs, (pair) => {
    if (typeof pair[1] != 'function') {
      throw new TypeError('Expected a function')
    }
    return [pair[0], pair[1]]
  })

  return (...args) => {
    for (const pair of pairs) {
      if (pair[0].apply(this, args)) {
        return pair[1].apply(this, args)
      }
    }
  }
}
  1. 利用map遍历进行了参数检查
  2. 利用apply调用

    示例


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

About Face 2.0

About Face 2.0

Alan Cooper、Robert M. Reimann / Wiley / March 17, 2003 / USD 35.00

First published seven years ago-just before the World Wide Web exploded into dominance in the software world-About Face rapidly became a bestseller. While the ideas and principles in the original book......一起来看看 《About Face 2.0》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具