下面的包含函数是基于.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);
};
答案 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)如果collection
为wasFound
,则< em>某些之前的true
与item
相同,因此将target
设置为wasFound
以维护它,(2)否则设置true
} {到wasFound
的价值。