美文网首页
lodash源码分析 --- (pull函数)

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

作者: shuta | 来源:发表于2018-07-03 12:02 被阅读0次

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 为啥?

相关文章

网友评论

      本文标题:lodash源码分析 --- (pull函数)

      本文链接:https://www.haomeiwen.com/subject/mrjduftx.html