javascript - 函数内的 Underscore.js 函数

标签 javascript underscore.js

  _.filter = function(collection, test) {
    var result = [];
    _.each(collection, function(value) {
      if(test(value)) {
        result.push(value);
      }
    })
    return result;
  };
  _.reject = function(collection, test) {
    var result = [];
    return _.filter(collection, function(value) {
      return !test(value);
    })
  };

我对它的工作原理有点困惑。我在同一范围内定义了两个 underscore.js 函数。如果我通过随机数字的测试数组,_.reject 中的 _.filter 如何工作?

var isEven = function(num) { return num % 2 === 0; };
var odds = _.reject([1, 2, 3, 4, 5, 6], isEven);
expect(odds).to.eql([1, 3, 5]);

例如,我测试我的函数,得到断言为 true,但我不明白这是如何工作的

最佳答案

Reject 只是重用过滤器完成的一些逻辑。它可以很容易地写成这样:

_.reject = function(collection, test) {
  var result = [];
  _.each(collection, function(value) {
    if(!test(value)) {
      result.push(value);
    }
  })
  return result;
};

您会注意到过滤器和拒绝之间的唯一区别是我们是否要在测试为真时保留项目,还是在测试为假时保留项目。

// Creates the function reject
_.reject = function(collection, test) {
  var result = [];

  // Calls filter but hands in a custom callback.
  // Filter iterates each item in the list, and keeps it
  // if test(item) returns true (test is our custom flipResult).
  // Remember that reject does the opposite, it keeps it
  // if test(item) returns false (aka !true).
  return _.filter(collection, function flipResult(value) {

    // The user gave us a test method. We want to keep items
    // that return false when passed to test.
    // If we call _.filter(collection, test) we will get all
    // items that return true when passed to test, but thats not what we want
    // So instead of handing test in directly, we hand in our custom callback
    // The custom callback calls test and flips the result.
    // This means filter will keep all items that return false
    // because our custom callback is flipping the result !test
    return !test(value);
  })
};

关于javascript - 函数内的 Underscore.js 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60482381/

相关文章:

javascript - 在 Underscore JS 中编写我的 _.reject 版本

javascript - JSFiddle - 使用 POST 请求错误

javascript - 检查 JS 数组中是否存在元素更好,还是添加它然后运行 ​​_.uniq 更好?

javascript - ExtJS 5 : Get initialConfig of defined class

javascript - Babel与browser.js并获得Uncaught SyntaxError : Invalid regular expression

javascript - backbone.js 中的 View 和附加表行

Javascript,下划线尝试返回具有最高值的对象的键

javascript - 覆盖 Backbone.js 比较器

javascript - 解决 AngularJS 中的多个 Promise

javascript - 异步/等待不等待 promise 完成