【问题标题】:What is the purpose of the following function in this code block?此代码块中以下函数的目的是什么?
【发布时间】:2014-03-13 18:32:53
【问题描述】:

我似乎无法弄清楚在 Eloquent Javascript 第 6 章的练习中包含以下代码块的实际重要性。

编辑:它不是必需的,而是允许从顶层调用它。

function countZeroes(array) {
  return count(equals(0), array);
}

这里是完整的代码:

function count(test, array) {
  return reduce(function(total, element) {
    return total + (test(element) ? 1 : 0);
  }, 0, array);
}

function equals(x) {
  return function(element) {return x === element;};
}

function countZeroes(array) {
  return count(equals(0), array);
}

这是之前的reduce函数:

function reduce(combine, base, array) {
  forEach(array, function (element) {
    base = combine(base, element);
  });
  return base;
}

这是前面的 forEach 函数:

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}

我才刚刚开始学习 JavaScript,所以我确信对此有一个简单的解释。谢谢。

【问题讨论】:

  • 你问countZeroes函数的意义是什么?如果您从不调用它,那么您可能不需要它。

标签: javascript function higher-order-functions


【解决方案1】:

永远不会调用该方法...

很可能是为了能够从顶层调用它。而不是:

show(count(equals(0), [2, 4, 5, 0, 3, 0, 0, 3]));

你可以有

var a = [1,4,5,0];
show( countZeroes( a ) );

【讨论】:

  • 这就是我要找的。我知道我忽略了一些非常简单的东西,即作者为什么会费心把它包括在内。谢谢。
【解决方案2】:

因为函数countZeros 从未调用过。

我认为原生函数Array.filter 更好/更快。

function count (whatToCount, theArrayToCount) {
    return theArrayToCount.filter (function (element) {
        // If they are same, keep; Otherwise remove from array
        return element === whatToCount;
    }).length; // Count the "filtered" Array, and return it.
}

count (0, [2, 4, 5, 0, 3, 0, 0, 3]); // 3

顺便说一句,回调令人困惑(..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 2017-11-04
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 2016-03-06
    相关资源
    最近更新 更多