Hier ist eine Kopie von flattenDeep()
in lodash, eine Funktion, die ein mehrdimensionales Array übergeben und ein neues Array zurückgeben, das abgeflacht wurde. Diese flattenDeep()
wird rekursiv behandelt.In lodash, warum sind die Prädikats- und Ergebnisvariablen nicht mit einem var Schlüsselwort vorangestellt?
Lesen des Quellcodes Ich bemerkte, dass:
predicate
und results
verwenden var nicht hinter ihnen?
predicate || (predicate = isFlattenable);
result || (result = []);
Frage: Warum lodash globale Variablen für Prädikat und Ergebnisse verwendet haben? Gibt es einen Grund/eine Theorie dahinter?
gezupft js:
var bigarray = [[1],[2,[3,3]],[1], 1];
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return Array.isArray(value);
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/**
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/
function flattenDeep(array) {
var length = array ? array.length : 0;
return length ? baseFlatten(array, Infinity) : [];
}
console.log(flattenDeep(bigarray));
Make benachrichtigt> _ <; Das war eine dumme Frage. –
nicht dumm ... schwitz es nicht! – JordanHendrix