3

获取数组的第一个元素。传递 n 将返回数组中的前 N ​​个值。别名为head and take。守卫检查允许它与 _.map 一起工作。

  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

这个 underscore.js 函数中的变量 'guard' 有什么用?

4

1 回答 1

3

如果您查看源代码:

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

警戒检查允许它与_.map.

因此,如果您有这样的数组:

var a = [ [1, 2, 3], [4, 5, 6] ];
// put this array though _.map and _.first
_.map(a, _.first); // [1, 4]

如果不是这种情况,您的结果将如下所示:

[ [], [4] ]

由于争论进入_.map

_.map(['a', 'b', 'c'], function(val, key, obj) {
    // key = 0, 1, 2
    // val = a, b, c
    // obj = ['a', 'b', 'c'] 
    // the obj argument is why `guard` is truly and the first element in the array is returned rater than using [].slice
});

它并不漂亮,但它允许它一起工作:

_.first([1, 2, 3], 2) // [1, 2]
_.first([1, 2, 3], 2, true) // 1
_.first([1, 2, 3], 2, 3) // 1
于 2013-09-05T15:12:22.853 回答