数组扁平化
-
使用
Array.prototype.flat当参数为
Infinity时可展开任意深度的嵌套数组并且移除数组中的空项,返回新数组
const flatten = (arr) => { return arr.flat(Infinity) } -
递归
-
concat -
push+...const flatten = (arr) => { const res = [] if (!Array.isArray(arr)) { return [arr] } else { for (let i = 0; i < arr.length; i++) { res.push(...flatten2(arr[i])) } } return res }
-
使用
Array.prototype.reduceconst flatten = (arr) => { return arr.reduce((prev, current) => { return prev.concat(Array.isArray(current) ? flatten(current) : current) }, []) } -
undercore
flatten的实现const flatten = (input, strict = false, output = []) => { let idx = output.length let inputLen = input.length for (let i = 0; i < inputLen; i++) { const element = input[i] if (Array.isArray(element)) { _flatten(element, strict, output) idx = output.length } else { // strict: flase直接加入,true跳过该元素 !strict && (output[idx++] = element) } } return output } -
Function.apply.call([].concat, [])const flatten9 = function (arg) { while (arg.some((item) => Array.isArray(item))) { arg = Function.apply.bind([].concat, [])(arg) } return arg }Function.apply.bind([].concat, [])通过
bind绑定 this([].concat),并将[]作为this传入apply中, 并预留出一个参数参数 而apply将参数数组中的元素作为单独的参数传入到 concat 中const arr = [1, 2, [3, 4, [5]]] const res1 = Function.apply.bind([].concat, [])(arr) const res2 = [].concat.apply([], arr)