_.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'的用途是什么?
最佳答案
如果您查看源代码:
// 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];
};
因此,如果您有一个像这样的数组:
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
关于javascript - 传递的参数 'guard'在underscore.js函数中检查什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18639936/