下划线每次检查{}返回回调 [英] underscore's each checking for {} return of callback
问题描述
我正在研究UnderscoreJS如何实现每个
/ forEach
I was examining how UnderscoreJS implements their each
/forEach
//somewhere up top:
var breaker = {};
//then the each function
var each = _.each = _.forEach = function (obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
//iterator = callback
//context = optional third parameter of each to provide context in the callback
//obj = the list
//key = key of the object (i for index when an array)
基本上,它正在为每个项执行回调在对象/数组中。但这就像让我感到困惑
Basically, it's executing the callback for each item in the object/array. But this like confuses me
if (iterator.call(context, obj[key], key, obj) === breaker) return;
根据我的理解,如果回调返回一个对象,循环会中断,但是...... 为什么它与断路器
比较,它是下划线模块中的内部对象?。它是否一直评估为 false
,即使回调确实返回了一个对象,它总是 false
因为它不是同一个对象(因此循环永远不会破坏)。这背后的原因是什么?
From what I understand, if the callback returns an object, the loop breaks, but... Why it's comparing to breaker
which is an internal object in the underscore module?. Doesn't it evaluate to false
all the time since, even if the callback does return an object, it is always false
since it's not the same object (therefore the loop never breaks). What's the reason behind this?
推荐答案
他们在内部使用每个
例如一些
。由于某些
会发生短路,他们可以使用秘密对象在每个
中断,而不会暴露这个常规用户的功能。它们不公开中断功能,因为本机函数也不会这样做(因此它们的垫片尽可能像本机一样)。如果他们这样做,那么只有当原生函数不可用时才能使用中断功能,这不是特别有用。
They use each
internally for e.g. some
. Since some
does short-circuit, they can have each
break there using the "secret" object, while not exposing this feature for regular users. They don't expose the break feature because the native function doesn't do that, either (so their shim is as native-like as possible). If they did, the break feature would only be available if the native function is unavailble, which isn't particularly helpful.
这篇关于下划线每次检查{}返回回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!