Javascript 传递的参数';防护罩';是否签入下划线.js函数?
获取数组的第一个元素。通过n将返回第一个n 数组中的值。化名为head和take。警卫检查允许 它可以与u.map一起工作Javascript 传递的参数';防护罩';是否签入下划线.js函数?,javascript,underscore.js,Javascript,Underscore.js,获取数组的第一个元素。通过n将返回第一个n 数组中的值。化名为head和take。警卫检查允许 它可以与u.map一起工作 变量“guard”在这个underline.js函数中有什么用途?如果您查看源代码: // 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
变量“guard”在这个underline.js函数中有什么用途?如果您查看源代码:
// 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] ]
如果不是这种情况,则结果如下所示:
var a = [ [1, 2, 3], [4, 5, 6] ];
// put this array though _.map and _.first
_.map(a, _.first); // [1, 4]
[ [], [4] ]
由于参数进入\uu.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
根据,
Array#map
将三个参数传递给回调,而不是两个:“callbackfn
由三个参数调用:元素的值、元素的索引和被遍历的对象。”@DCoder这是正确的,这就是.first
函数返回第一个值的原因:)谢谢