我正在尝试从 Eloquent Javascript 一书中理解这种功能样式代码:
http://eloquentjavascript.net/chapter6.html#exercise1
当 count() 函数将匿名函数传递给 reduce() 时,代码会起作用。但是,如果我将函数分解为辅助函数,则会出现参考错误。
谁能解释为什么 count() 有效但 countHelper() 无效?
var numbers = [1,2,3,0,1,2,3,0]
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element);
});
return base;
}
function equals(x) {
return function(element) { return x === element;};
}
function count(test, array) {
return reduce(function(base, element) {
return base + (test(element)?1:0);
}, 0, array);
}
function countHelper(test, array) {
function helper(base, element) {
return base + (test(element)?1:0);
}
return reduce(helper(base, element), 0, array);
}
function countZeroes(array) {
return count(equals(0), array);
}
print(countZeroes(numbers)) // 2
function countZeroesHelper(array) {
return countHelper(equals(0), array);
}
print(countZeroesHelper(numbers)) // ReferenceError: base is not defined