继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

每天一个lodash方法(6)

Qyouu
关注TA
已关注
手记 311
粉丝 87
获赞 413

fromPairs

功能:将数组解析成对象。

@pairs: 需要解析的键值对数组
@result: 返回的对象function fromPairs(pairs) {      var index = -1,
          length = pairs == null ? 0 : pairs.length,
          result = {};     // 遍历数组,对象赋值
      while (++index < length) {        var pair = pairs[index];
        result[pair[0]] = pair[1];
      }      return result;
    }

indexOf

功能:从指定位置(fromIndex,默认为0)开始查询数组array中第一个值为value的元素,返回该元素下标。

function indexOf(array, value, fromIndex) {  const length = array == null ? 0 : array.length  if (!length) {    return -1
  }
  let index = fromIndex == null ? 0 : +fromIndex  // 确定起始位置,并对位置进行判断
  if (index < 0) {
    index = Math.max(length + index, 0)
  }  // 核心查询方法
  return baseIndexOf(array, value, index)
}// baseIndexOffunction baseIndexOf(array, value, fromIndex) {  // 根据类型的不同,执行不同的查找方法,但是核心查找方法都是遍历比较
  return value === value
    ? strictIndexOf(array, value, fromIndex)
    : baseFindIndex(array, baseIsNaN, fromIndex)
}// strictIndexOffunction strictIndexOf(array, value, fromIndex) {
  let index = fromIndex - 1
  const { length } = array

  while (++index < length) {    if (array[index] === value) {      return index
    }
  }  return -1}// baseFindIndex类似,不同之处在于将判断相等变成了谓词判定

initial

功能:返回数组除最后一个之外的所有元素。
方法:slice切割。

 function initial(array) {  const length = array == null ? 0 : array.length  return length ? slice(array, 0, -1) : []
}



作者:公子七
链接:https://www.jianshu.com/p/b32331ebd885


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP