创建简化的下划线 _.invoke



我正在尝试创建下划线的_.invoke函数。我不知道为什么我总是收到类型错误,无法读取未定义的属性"排序"。我假设这是指传递给函数的数组,但我可以记录集合中的每个数组,所以我不知道为什么在抛出时未定义。

function each(collection, iteratee, context) {
  let i
  let boundIteratee = iteratee.bind(context)
  if (Array.isArray(collection)) {
    for (i = 0; i < collection.length; i++) {
      boundIteratee(collection[i], i, context)
    }
  } else {
    for (i in collection) {
      if (collection.hasOwnProperty(i)) {
        boundIteratee(collection[i], i, collection);
      }
    }
  }
  return collection
}
function map(collection, iteratee, context) {
  let result = []
  let formula = function(element, index) {
    result.push(iteratee(element, index, context))
  }
  each(collection, formula, context)
  return result
}
function invoke(collection, methodName) {
  let args = Array.prototype.slice.call(arguments, 2)
  let formula = function(array, index) {
    //console.log(array) --> returns arrays in collection...
    return methodName.apply(array, args)
  }
  return map(collection, formula)
}
function sortIt(array) {
  return array.sort()
}
console.log(invoke([
  [3, 1, 2],
  [7, 6, 9]
], sortIt))

根据您要实现的目标,您可以将sortIt函数替换为:

function sortIt() { return this.sort(); } // since you apply the arrays as context to the function

或替换

return methodName.apply(array, args);

return methodName(array);

不过,两者都不理想。

另外,请查找 apply(( 方法。

最新更新