本系列使用 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 数组由剩下的元素组成。
三、函数工作原理
-
判断参数合法性, 若数组 array 为空,则返回空数组 result;
if (!(array != null && array.length)) { return result复制代码
} ```
- 遍历数组;
while (++index < length) { const value = array[index] if (predicate(value, index, array)) { result.push(value) indexes.push(index) } }复制代码
-
把由 predicate 过滤为真值的元素放入新数组 result 中;
-
把遍历的索引 index 放入 indexs 中;
- 移除数组在 indexs 中对应索引的元素,并返回这些元素.
basePullAt(array, indexes)复制代码
本文章来源于午安煎饼计划Web组 - 初见
相关链接: