lodash源码分析 --- (pull函数)

pull函数

我的写法

function pull(array, ...values) {
    let result = []

    console.log(values)
    outer:
    for(val of array) {
        for(let oldVal of values) {
            if (val == oldVal) {
                continue outer
            }   
        }

        result.push(val)

    }

    return result
}

我这个没有改变原数组哈。。。

别人的写法

function basePullAll(array, values, iteratee, comparator) {
  const indexOf = (array, value, fromIndex)  =>{
     let index = fromIndex - 1
     const { length } = array

      while (++index < length) {
        if (array[index] === value) {
          return index
        }
      }
    return -1
  }
  const length = values.length

  let index = -1
  let seen = array

  while (++index < length) {
    let fromIndex = 0
    const computed = values[index]

    while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
      array.splice(fromIndex, 1)
    }
  }
  return array
}

感想

  • 剩余参数 用于不定数量的参数十分有用.
  • 在js中,object和array传入function时,传入的是引用。所以对array进行push/pull/splice的操作,会影响到原数组。js中function的形参
  • 我唯一不能理解的是在lodash中有这种代码value === value 为啥?
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。