2017-04-07 12 views
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))

+0

終了文の習慣を ';'で覚えてください。セミコロンの自動挿入は、必ずしもあなたが期待することをするわけではありません。 – Barmar

+0

問題は、決して配列を 'sortIt'関数に渡さないことです。あなたの 'args'はあなたがソートしようとしているコレクションを含んでいません。 – nainy

答えて

1

あなたが達成しようとしている内容に応じて、あなたがあなたの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()メソッドを参照してください。

関連する問題