数组扁平化
1.ES6 flat
flat(depth) 参数:depth
返回值:返回一个新数组,包含数组与提取嵌套数组的所有元素的新数组
function flatten(params){
return params.flat(Infinity)
}
2.toString
如果数组的项全为数字,可以使用jion(),tostring()转为字符串
function flatten(arr){
return arr.toString().split(',').map(item => parseFloat(item))
}
3.使用正则替换
4.循环递归
思路:循环判断数组的每一项是否是数组:Array.isArray(arr[i])
是数组就递归调用上面的扁平化一层的代码 result = result.concat(flatten(arr[i]))
不是数组,直接通过push添加到返回数组
function flatten(arr){ let res = [] arr.forEach(item => { if(Array.isArray(item)){ result = result.concat(flatten(item)) }else{ res.push(item) } }) return res }
增加参数控制扁平化深度 手写flat
const eachFlat = (arr = [], depth = 1) => { const result = [] (function flat(arr,depth) { arr.forEach((item) => { if(Array.isArray(item) && depth > 0){ flat(item,depth - 1) }else{ result.push(item) } }) })(arr,depth) return result }

浙公网安备 33010602011771号