试图理解这个.contain()函数的语法

时间:2015-12-08 20:33:43

标签: javascript callback

下面的包含函数是基于.reduce()函数编写的:

 _.reduce = function(collection, iterator, accumulator) {
  each(collection,function(value){
    accumulator=iterator(accumulator,value);

  });
  return accumulator 
  };

我对这里的语法感到困惑,还是逻辑上写的?为什么我们首先使用if语句并返回' wasFound'首先,在设置项目===目标之前?如果item === target为true,我们将wasFound设置为true?

     _.contains = function(collection, target) {
        return _.reduce(collection, function(wasFound, item) {
          if (wasFound) {
            return true;
          }
          return item === target;
        }, false);
      };

2 个答案:

答案 0 :(得分:1)

^ Anchor to the beginning of the line .* Followed by zero or more of any characters [>;] Followed by a character class consisting of a greater-than sign or a semi-colon (.*lib1.*?) Followed by a remembered group of zero or more characters followed by the desired "lib1" followed by optional zero or more characters [;<] Followed by a character class consisting of a semi-colon or a less-than sign 函数第一次进行匹配(reduce)时,对于要迭代的所有剩余项,它将随后返回true。没有理由检查未来的值是否与目标匹配,因为我们只关心集合是否包含目标至少1次。这就是为什么如果return item === target为真,它只返回true。

答案 1 :(得分:0)

你这样使用它:

private void mainTaskLoader() {
     Task initialLoad = new Task(performInitialTagLoad);
     initialLoad.Start();
     Task dataHarvester = new Task(() => {
          Task.WhenAll(initialLoad);
     }).ContinueWith(t => initializeDataHarvester());         
}

private void performInitialTagLoad() {
   allTags = globals.getTags();
   foreach (KeyValuePair<String, String> tag in allTags) {
       try {
           globals.insertUpdateHarvesterData(tag.Key.ToString(), commObject.Read(tag.Value.ToString()));
       } catch (Exception e) {
           Console.WriteLine("Error on initial load: " + e.Message, true);                    
       }
   }
   Console.WriteLine("Initial tag data load complete");         
}

private void initializeDataHarvester() {
        Console.WriteLine("Got here!");            
}

它需要一个列表和一个元素。它最初将_.contains([1,2,3], 2); //=> true _.contains([1,2,3], 5); //=> false 设置为wasFound,然后针对false检查中的每个item设置:(1)如果collectionwasFound,则< em>某些之前的trueitem相同,因此将target设置为wasFound以维护它,(2)否则设置true } {到wasFound的价值。