创建简化的下划线_.invoke

时间:2017-04-07 16:22:54

标签: javascript function underscore.js

我正在尝试创建下划线的_.invoke函数。我无法弄清楚为什么我一直得到一个TypeError,无法读取未定义的属性'sort'。我假设这是指传递给函数的数组,但是我可以在集合中记录每个数组,所以我不知道为什么在被抛出时未定义。

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))

1 个答案:

答案 0 :(得分:1)

根据您要实现的目标,您可以将LIBS += ws2_32.lib 功能替换为:

sortIt

或替换

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

return methodName.apply(array, args);

但两者都不是理想的。

另外,请查看apply()方法。