写个函数实现数组拍平
let arr = [3, 4, [4, 5, ['s']]] function flat(arr) { //... } flat(arr) //[3, 4, 4, 5, 's']
let arr = [3, 4, [4, 5, ['s']]] arr.flat(2) //拍平2层, 不加参数默认拍平1层 arr.flat(Infinity) // 拍平任意层
let arr = [3, 4, [4, 5, ['s']]] function flat(arr) { let tmp = [] arr.forEach(v => { tmp = tmp.concat(Array.isArray(v)?flat(v):v) }) return tmp } flat(arr) //[3, 4, 4, 5, 's']
在原数组上操作
let arr = [3, 4, [4, 5, ['s']]] function flat(arr) { let i = 0 while(i < arr.length) { if(Array.isArray(arr[i])) { let tmp = flat(arr[i]) arr.splice(i, 1, ...tmp) i += tmp.length } i++ } return arr } flat(arr) //[3, 4, 4, 5, 's']
let arr = [3, 4, [4, 5, ['s']]] function flat(arr) { let i = 0 while(i < arr.length) { if(Array.isArray(arr[i])) { let tmp = flat(arr[i]) arr.splice(i, 1, ...tmp) i += tmp.length - 1 //这里修正 } i++ } return arr } flat(arr) //[3, 4, 4, 5, 's']
第8行修正为 i += tmp.length - 1