javascript - 传递的参数 'guard' 在 underscore.js 函数中检查什么?

标签 javascript underscore.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];
  };

在这个 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];
  };

The guard check allows it to work with _.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

关于javascript - 传递的参数 'guard' 在 underscore.js 函数中检查什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18639936/

相关文章:

javascript - 如何在单击时更改 div 的位置并在再次单击时按原样移动?

javascript - 从 API 中提取信息并将其添加到数据库(MEAN 堆栈)

javascript - 从 underscore.js 转换为 vanilla javascript

jquery - 根据一个元素css分离ul

node.js - 尝试在多维数组中使用 .sortBy

javascript - 为什么下划线使用 `root` 而不是 `this` ?

javascript - underscore.js - 组合模板

javascript - 如何在服务器端 Blazor 中使用 Bing Javascript map ?

javascript - 找不到输入字符串中写入的特定字符

javascript - 使用 Moment's guess() 返回时区名称