我有一些代码(已经提供并且需要为它添加代码以便它可以工作。下面的所有函数必须保留(它只是练习),最后一个函数(reduce函数)通过2个测试:
reduce([3, 5, 7], 0, adding); // works
reduce(["hey whats up", "this is a test"], 0, countingWords); // doesn not work
我认为必须更改countWords,因此reduce函数适用于两种情况
var adding = function(a, b) { //this function was provided
return a + b;
};
function counting(string){ //this function must stay too
var words;
if (typeof string==='string') {
words=string.split(" ");
}
else {
words=string.join(" ").split(" ");
}
return words.length;
}
//counting("this is a sentence"); // should return 4 and it does -all good
function countingWords(words) { //must stay
return counting(words);
}
function reduce(array,initial,func){
var current=initial;
for (var i=0; i<array.length; i++){
current=func(current,array[i]);
}
return current;
}
reduce([3, 5, 7], 0, adding); // works
reduce(["hey whats up", "this is a test"], 0, counting); // doesn not work
非常感谢有关改变的帮助或建议!!