0
アンダースコアの_.invoke関数を作成しようとしています。なぜ私はTypeErrorを取得し続けているのか分からず、未定義のプロパティ 'sort'を読み込めません。私はこれが関数に渡されている配列を参照していると仮定しますが、コレクション内の各配列をログに記録できるので、なぜスローされるのが未定義であるのか分かりません。簡略化されたアンダースコアの作成_.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))
終了文の習慣を ';'で覚えてください。セミコロンの自動挿入は、必ずしもあなたが期待することをするわけではありません。 – Barmar
問題は、決して配列を 'sortIt'関数に渡さないことです。あなたの 'args'はあなたがソートしようとしているコレクションを含んでいません。 – nainy