_.pullAll(array, values)

29

_.pullAll(array, values)

_.pullAll方法和pull类似,删除数组里的给定元素,区别是pull传递的要删除的元素是一个一个参数,pullAll传递的是数组

参数

array (Array): 要修改的数组
values (Array): 要被删除的元素组成的数组

返回值

(Array):返回删除元素后的原数组

例子

var array = ['a', 'b', 'c', 'a', 'b', 'c'];
 
_.pullAll(array, ['a', 'c']);
console.log(array);
// => ['b', 'b']

源代码:

pullAll和pull源代码差不多一样,所以省略其他细节

import basePullAll from './.internal/basePullAll.js'

/**
 * This method is like `pull` except that it accepts an array of values to remove.
 *
 * **Note:** Unlike `difference`, this method mutates `array`.
 *
 * @since 4.0.0
 * @category Array
 * @param {Array} array The array to modify.
 * @param {Array} values The values to remove.
 * @returns {Array} Returns `array`.
 * @see pull, pullAllBy, pullAllWith, pullAt, remove, reject
 * @example
 *
 * const array = ['a', 'b', 'c', 'a', 'b', 'c']
 *
 * pullAll(array, ['a', 'c'])
 * console.log(array)
 * // => ['b', 'b']
 */
//和pull类似,删除数组里的给定元素,和difference不同,这个方法会改变原数组
function pullAll(array, values) {
  return (array != null && array.length && values != null && values.length)
    ? basePullAll(array, values)
    : array
    //如果array不是null,并且array有元素,并且values不为null,并且values有元素,就调用basePullAll
    //否则返回原数组
}

export default pullAll

basePullAll

import map from '../map.js'
import baseIndexOf from './baseIndexOf.js'
import baseIndexOfWith from './baseIndexOfWith.js'
import copyArray from './copyArray.js'

/**
 * The base implementation of `pullAllBy`.
 *
 * @private
 * @param {Array} array The array to modify.
 * @param {Array} values The values to remove.
 * @param {Function} [iteratee] The iteratee invoked per element.
 * @param {Function} [comparator] The comparator invoked per element.
 * @returns {Array} Returns `array`.
 */
//pullAllBy方法的基础实现
//array要修改的数组,values要删除的元素,iteratee迭代器,comparator比较器
function basePullAll(array, values, iteratee, comparator) {
  const indexOf = comparator ? baseIndexOfWith : baseIndexOf//有没有传递自定义比较器的处理
  const length = values.length//要删除的元素的长度

  let index = -1//循环索引
  let seen = array

  if (array === values) {//如果array和values严格相等,就复制一份新的values,以防array和values被同时改变
    values = copyArray(values)
  }
  if (iteratee) {
    seen = map(array, (value) => iteratee(value))//用迭代器处理array生成新的数组
  }
  while (++index < length) {//循环values查找相同的元素然后splice剪切掉
    let fromIndex = 0
    const value = values[index]//需要查找的要被删除的值
    const computed = iteratee ? iteratee(value) : value//迭代器处理当前要被删除的值

    while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
      //用baseIndexOf查找computed在seen中的位置,如果找到了,就从seen和array里都删除掉
      if (seen !== array) {
        seen.splice(fromIndex, 1)
      }
      array.splice(fromIndex, 1)
    }
  }
  return array
}

export default basePullAll

 

posted @ 2018-10-16 10:18  hahazexia  阅读(1171)  评论(0)    收藏  举报