我一直在阅读 Underscore 库源代码,并遇到了这个:
_.iteratee = builtinIteratee = function(value, context) {
return cb(value, context, Infinity);
};
将 Infinity
作为参数是什么意思?
编辑:
对不起,这里是cb
和optimizeCb
。他们将回调转换为适当的迭代器。
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount) {
case 1: return function(value) {
return func.call(context, value);
};
// The 2-parameter case has been omitted only because no current consumers
// made use of it.
case null:
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// An internal function to generate callbacks that can be applied to each
// element in a collection, returning the desired result — either `identity`,
// an arbitrary callback, a property matcher, or a property accessor.
var cb = function(value, context, argCount) {
if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value) && !_.isArray(value)) return _.matcher(value);
return _.property(value);
};
最佳答案
Infinity
被解释为一个数字。在这种情况下,来源指向这里:
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
// The 2-argument case is omitted because we’re not using it.
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
注意 Infinity
被传递给参数 argCount
。 switch/case 语句将退出并返回一个函数,该函数将简单地将上下文和参数应用于回调函数。使用 Infinity
似乎可以确保 fall-through case。
关于javascript - 无穷大作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52921944/