数组字符串化
- 首先使用join把数组转成字符串
- 然后再使用split切割成数组
缺点:会把数字转成字符串
var arr = [3, 4, 5, 6, [7, 8, [9, 10, 2, [3, 4, 5, 2]]]]arr = arr.join(',').split(',')console.log(rr)
使用递归实现降维
var arr = [3, 4, 5, 6, [7, 8, [9, 10, 2, [3, 4, 5, 2]]]]let newArr = []function flat(arr) { arr.forEach(function (item) { item instanceof Array ? flat(item) : newArr.push(item) })}flat(arr)console.log(newArr)
使用reduce实现降维
function flat(arr) { let newArr = arr.reduce( (start, current) => Array.isArray(current) ? start.concat(...flat(current)) : start.concat(current), [] ) return newArr}let newArr = flat(arr)console.log(newArr)
使用ES6的flat方法降维
var arr = [3, 4, 5, 6, [7, 8, [9, 10, 2, [3, 4, 5, 2]]]]const newArr = arr.flat(Infinity);console.log(newArr);