本系列使用 lodash 4.17.4版本數組
源碼分析不包括引用文件分析bash
1、源碼函數
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
複製代碼
2、函數做用源碼分析
函數引用示例:post
var _= require('lodash');
//using remove.js
const array = [1, 2, 3, 4]
const evens = _.remove(array, n => n % 2 == 0)
console.log(array)
// => [1, 3]
console.log(evens)
// => [2, 4]
複製代碼
從上面的例子能夠看出:ui
remove 函數共有兩個參數,即 array 和 predicate 。this
array 參數傳入的是一個數組,predicate 傳入的是一個函數。spa
remove函數 的返回結果就是經 predicate 處理後爲真的元素組成的數組,即被移除的元素組成的新數組。.net
被相應移除元素後,array 數組由剩下的元素組成。code
3、函數工做原理
判斷參數合法性, 若數組 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 中;
basePullAt(array, indexes)
複製代碼
本文章來源於午安煎餅計劃Web組 - 初見
相關連接: