重新创建underscore.js'拒绝'使用'过滤器'

时间:2015-08-05 15:48:49

标签: javascript underscore.js

我有一个项目,要求我复制下划线.js'拒绝'功能使用'过滤器'功能。我已经写了以下内容,但似乎无法通过测试。有什么建议?

// Return all elements of an array that pass a truth test.
  _.filter = function(collection, test) {
    var passed = [];
    _.each(collection, function(item, index) {
      if (test(item) === true) {
        passed.push(item);
      }
    });
    return passed;
  };

  // Return all elements of an array that don't pass a truth test.
  _.reject = function(collection, test) {
    _.filter(collection, function(item) {
      return !test(item);
    });
  };

1 个答案:

答案 0 :(得分:1)

您忘记返回filter的结果。

_.reject = function(collection, test) {
  return _.filter(collection, function(item) {
    return !test(item);
  });
};