Open xiaokeqi opened 4 years ago
lodash 也是通过递归实现
function baseFlatten(array, depth, predicate, isStrict, result) {
predicate || (predicate = isFlattenable)
result || (result = [])
if (array == null) {
return result
}
for (const value of array) {
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result)
} else {
result.push(...value)
}
} else if (!isStrict) {
result[result.length] = value
}
}
return result
}
es6新方法 arr.flat 如:
var arr = [1,[2,3,[4,[5,6,[7]]]]];
arr.flat(Infinity) // 1234567
var arr = [1,[2,3,[4,[5,6,[7]]]]];
自己的实现方法是通过reduce和concat方法,递归遍历,实现扁平化