繁体   English   中英

为什么_.some在没有迭代器函数的情况下运行?

[英]Why does _.some run when there is no iterator function?

如果你使用循环的习惯用法,如_.some() ,但没有传入迭代器函数, _.some()出错了。 然而,下划线将用身份功能取代它并继续运行。

这是为什么:从下划线

  var any = _.some = _.any = function(obj, iterator, context) {
    iterator || (iterator = _.identity); // this line?
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
    each(obj, function(value, index, list) {
      if (result || (result = iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

案例用法:

_.some([0,1,2,3], null);

但是不要传递迭代器函数出错的地方。

一点也不。 iterator是一个可选参数,默认情况下, _.some()将自己测试集合的元素是否真实 在文档中得到证明

_.some([null, 0, 'yes', false]);
=> true

iterator只允许您指定自己的条件:

_.some([ 1, 2, 3, 4, 5 ], function (x) { return x > 6; })
=> false

包括测试元素成员的真实性

_.some([ { value: 0 }, { value: 1 } ], function (x) { return x.value; });
=> true

因为..为什么不应该运行?

这是一个API设计选择 ,只是让它“早退”(与正常应用识别功能相比) 会改变行为 这是因为身份函数有效地传递了值的真实性(假性):

_.some([0,undefined,null,""]) // false
_.some([1])                   // true

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM