博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
每日源码分析 - Lodash(remove.js)
阅读量:7210 次
发布时间:2019-06-29

本文共 2042 字,大约阅读时间需要 6 分钟。

本系列使用 lodash 4.17.4版本

源码分析不包括引用文件分析

一、源码

import basePullAt from './.internal/basePullAt.js'/** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `filter`, this method mutates `array`. Use `pull` * to pull elements from an array by value. * * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @see pull, pullAll, pullAllBy, pullAllWith, pullAt, reject, filter * @example * * const array = [1, 2, 3, 4] * const evens = remove(array, n => n % 2 == 0) * * console.log(array) * // => [1, 3] * * console.log(evens) * // => [2, 4] */function remove(array, predicate) {  const result = []  if (!(array != null && array.length)) {    return result  }  let index = -1  const indexes = []  const { length } = array  while (++index < length) {    const value = array[index]    if (predicate(value, index, array)) {      result.push(value)      indexes.push(index)    }  }  basePullAt(array, indexes)  return result}export default remove复制代码

二、函数作用

函数引用示例:

var _= require('lodash');//using remove.jsconst array = [1, 2, 3, 4]const evens = _.remove(array, n => n % 2 == 0)console.log(array)// => [1, 3]console.log(evens)// => [2, 4]复制代码

从上面的例子可以看出:

  • remove 函数共有两个参数,即 array 和 predicate 。

  • array 参数传入的是一个数组,predicate 传入的是一个函数。

  • remove函数 的返回结果就是经 predicate 处理后为真的元素组成的数组,即被移除的元素组成的新数组。

  • 被相应移除元素后,array 数组由剩下的元素组成。

三、函数工作原理

  1. 判断参数合法性, 若数组 array 为空,则返回空数组 result;

    if (!(array != null && array.length)) {    return result复制代码

} ```

  1. 遍历数组;
while (++index < length) {    const value = array[index]    if (predicate(value, index, array)) {      result.push(value)      indexes.push(index)    }  }复制代码
  • 把由 predicate 过滤为真值的元素放入新数组 result 中;

  • 把遍历的索引 index 放入 indexs 中;

  1. 移除数组在 indexs 中对应索引的元素,并返回这些元素.
basePullAt(array, indexes)复制代码

本文章来源于午安煎饼计划Web组 - 初见

相关链接:

转载地址:http://mzgum.baihongyu.com/

你可能感兴趣的文章
为啥说5G是“全村人的希望” 2018年5G产业大盘点 ...
查看>>
阿里云备案服务号申请方法及申请条件
查看>>
鲜为人知的混沌工程,到底哪里好?
查看>>
AI技术普及,直播平台源码开发市场发展可期
查看>>
【MaxCompute季报】MaxCompute新功能发布 2018Q4
查看>>
虚拟化架构种类、特点及优势
查看>>
可爱的python 大合集
查看>>
java学习计划
查看>>
java反射机制
查看>>
井盖智能化升级最佳实践
查看>>
阿里云服务器部署Java Web项目全过程
查看>>
一个限制进程 CPU 使用率的解决方案
查看>>
HBase-拆分合并和调优参考
查看>>
SQL得到任意一个存储过程的参数列表sp_procedure_params_rowset
查看>>
redis rdb持久化
查看>>
拾叶集 - 江湖一剑客
查看>>
WPF DataTomplate中Command无效
查看>>
【对讲机的那点事】带你玩转手机对讲(下)
查看>>
Bmp图片的结构剖析与代码处理实践[Ruby]
查看>>
不一样的厦门,不一样的旅行!
查看>>