如果您查看源代码:
// 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