我试图重新创建reduce方法,但是作为原始函数。
这让我了解了很多,但我有一个小问题: 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 :(得分: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