2015-12-30 33 views
0

我試圖重新創建reduce方法,但是作爲原始函數。重新創建JavaScript的縮小函數

這幫助我瞭解了很多,但我有一個小問題: How to re-create Underscore.js _.reduce method? 當我插上陣列它的作品的權利,但對象不工作。我弄不明白。對於我應該改變的內容,我將不勝感激。我評論了我認爲應該改變的地方,但我很困惑我需要改變它。我也創建了我自己的每個功能。

你可以在這裏找到我的代碼:http://goo.gl/6RU9Bc

任何意見將是超級有用。謝謝!!

這是我到目前爲止有:

var myArray=[1,2,3,4,5]; 

var myObject={ 
    num1:1, 
    num2:2, 
    num3:3 
}; 

function each(collection, callback){ 
    if(Array.isArray(collection)) { 
    for(var i=0, l=collection.length; i<l; i++){ 
     callback(collection[i]); 
    }; 
    }else if(collection === "object") { 
    for(var prop in collection){ 
     callback(collection[prop]); 
    }; 
    } 
} 

function multiply(num, num2){ 
    return num*num2; 
} 

function reduce(collection, callback, accumulator){ 
    each(collection, function(element){ 
    if(accumulator === undefined) { 
     return accumulator = element; // is the problem here? Why? I don't understand. 
    }else { 
     return accumulator = callback(accumulator, element); 
    }; 
}); 

return accumulator; 
}; 

console.log(reduce(myArray, multiply)); // 120 
console.log(reduce(myArray, multiply, 5)); // 160 
console.log(reduce(myObject, multiply)); // returns undefined 
console.log(reduce(myObject, multiply, 5)); // returns 5 
+0

FWIW,MDN有[可用polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Polyfill) - 可能能夠獲得一些想法。 –

+3

'if(collection ===「object」)'永遠不會是真的。它不應該是'typeof(collection)==='object')'? –

+0

是的,你完全正確。有人告訴我,當我做每個功能時都會選擇這種類型,因爲它不是必需的。謝謝! – Masha

回答

0

正如@Yeldar Kurmangaliyev指出的那樣,你需要改變這一點:

if(collection === "object") 

到:

if(typeof(collection) === "object") 

這裏是固定代碼:

var myArray=[1,2,3,4,5]; 

var myObject={ 
    num1:1, 
    num2:2, 
    num3:3 
}; 

function each(collection, callback){ 
    if(Array.isArray(collection)) { 
    for(var i=0, l=collection.length; i<l; i++){ 
     callback(collection[i]); 
    }; 
    }else if(typeof(collection) === "object") { 
    for(var prop in collection){ 
     callback(collection[prop]); 
    }; 
    } 
} 

function multiply(num, num2){ 
    return num*num2; 
} 

function reduce(collection, callback, accumulator){ 
    each(collection, function(element){ 
    if(accumulator === undefined) { 
     return accumulator = element; // is the problem here? Why? I don't understand. 
    }else { 
     return accumulator = callback(accumulator, element); 
    }; 
}); 

return accumulator; 
}; 

console.log(reduce(myArray, multiply)); // 120 
console.log(reduce(myArray, multiply, 5)); // 600 
console.log(reduce(myObject, multiply)); // 6 
console.log(reduce(myObject, multiply, 5)); // 30