Underscore 源码解读 - 内部函数

Underscore - 内部函数

restArgs(剩余参数)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 类似于 ES6's 剩余参数 (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// func 的形参数不定,把传入不定数量的实参添加到一个数组中,成为一个实参数组,可设置起始下标。
var restArgs = function(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
case 2: return func.call(this, arguments[0], arguments[1], rest);
}
var args = Array(startIndex + 1);
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index];
}
args[startIndex] = rest;
return func.apply(this, args);
};
};

flatten(扁平化)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, output) {
output = output || [];
var idx = output.length;
for (var i = 0, length = getLength(input); i < length; i++) {
var value = input[i];
// 判断 value 类型
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
// Flatten current level of array or arguments object.
if (shallow) { //当 shallow 为 true 时,只扁平化一层。
var j = 0, len = value.length;
while (j < len) output[idx++] = value[j++];
} else { // 递归扁平化。
flatten(value, shallow, strict, output);
idx = output.length;
}
} else if (!strict) { // 当 strict 为 true 时,不会把非数组的 value 追加到 output 中。
output[idx++] = value;
}
}
return output;
};