簡體   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