Array.flat原理实现 发表于 2019-06-25 | 分类于 Coding | 阅读次数: Array.flat实现1// input [1, 2, [3, 4, [5, 6, 7]], 8] -> output [1, 2, 3, 4, 5, 6, 7, 8]; 1234567891011121314151617181920interface Array<T> { flatInfinity(): T[]; flat(n?: number): T[];}Array.prototype.flatInfinity = function() { const stack = [...this]; const value = []; while (stack.length) { const next = stack.pop(); if (Array.isArray(next)) { stack.push(...next); } else { value.push(next); } } return value.reverse();};Array.prototype.flat = function(n = 1) { return baseFlatten(this, n, []);}; baseFlatternlodash.js12345678910111213141516171819202122232425/** * 将数组拉平 * @param {Array} array 需要拉平数组 * @param {number} depth 数组的深度 * @param {Array} result 初始化将要返回的数组 * @returns {Array} 返回扁平后的数组 */function baseFlatten(array, depth, result) { result || (result = []); if (array == null) { return result; } for (const value of array) { if (depth > 0 && Array.isArray(value)) { if (depth > 1) { baseFlatten(value, depth - 1, result); } else { result.push(...value); } } else { result[result.length] = value; } } return result;}