[Underscore.js函数内的函数

问题描述 投票:0回答:2
  _.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]);

例如,我测试了我的函数,并得到了断言为真,但我不明白其工作原理

javascript underscore.js
2个回答
1
投票

拒绝只是重复使用过滤器完成的某些逻辑。它很容易以这种方式编写:

_.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);
  })
};

0
投票

例如,如果您的数字数组是:

const nums = [1, 2, 3, 4, 5, 6]

并且您有一个函数isEven,该函数接受一个数字,如果它是偶数,则返回true;如果它不是偶数(即,奇数),则返回false

function isEven(num) {
  return num % 2 === 0;
}

然后运行_.filter(arr, isEven)将执行以下逻辑:

  • [arrcollection的名称和isEventest的名称
  • 声明一个名为result的数组。
  • 遍历偶数中的每个数字

    • 对于每个数字(value),检查调用test(value)是否给出true的结果。
    • 如果test(value)为真,则将数字(value)添加到result数组的末尾。
    • 转到数组collection中的下一个数字
  • 返回result数组。

因此,filter()对数组中的每个数字执行isEven函数,如果返回true,则将其添加到新数组中(即:将其保留)。

_.reject()_.filter()的作用相反-也就是说,它保留了回调函数为其返回false的所有元素。如您所知_.filter()保留为其返回true的值,您可以通过取反_.filter()返回的布尔值来使用test(value)。这样,当test(value)返回false时,可以将其取为true,使_.filter()方法保留该元素。如果test(value)返回true,则将其取为false,使过滤器方法放弃该value

© www.soinside.com 2019 - 2024. All rights reserved.