(1)数组字符串化
<script>
// 数组字符串化
let arr =[[222,333,444],[555,666,77]]
arr+=''
arr=arr.split(',')
console.log(arr)
</script>
(2)递归
<script>
// // (1)数组字符串化
// let arr =[[222,333,444],[555,666,77]]
// arr+=''
// arr=arr.split(',')
// console.log(arr)
// (2)递归
let arr =[[222,333,444],[555,666,77]]
function reduceDimension(arr1) {
let ret = []
let toArr = function (arr1) {
arr1.forEach(function (item) {
item instanceof Array ? toArr(item) : ret.push(item)
})
}
toArr(arr)
return ret
}
console.log(reduceDimension(arr))
</script>
(3)Array.prototype.flat()
<script>
// // (1)数组字符串化
// let arr =[[222,333,444],[555,666,77]]
// arr+=''
// arr=arr.split(',')
// console.log(arr)
// (2)递归
// let arr =[[222,333,444],[555,666,77]]
// function reduceDimension(arr1) {
// let ret = []
// let toArr = function (arr1) {
// arr1.forEach(function (item) {
// item instanceof Array ? toArr(item) : ret.push(item)
// })
// }
// toArr(arr)
// return ret
// }
// console.log(reduceDimension(arr))
// (3)Array.prototype.flat()
let arr1 = [1, 2, [3, 4]]
console.log(arr1.flat()) //[1,2,3,4]
let arr2 = [1, 2, [3, 4, [5, 6]]]
console.log(arr2.flat())//[1,2,3,4,5,6]
let arr3 = [1, 2, [3, 4, [5, 6]]]
console.log(arr3.flat(Infinity))//[1,2,3,4,[5,6]]
</script>
(4)使用reduce,concat和递归无限反嵌套多层嵌套数组
<script>
// // (1)数组字符串化
// let arr =[[222,333,444],[555,666,77]]
// arr+=''
// arr=arr.split(',')
// console.log(arr)
// (2)递归
// let arr =[[222,333,444],[555,666,77]]
// function reduceDimension(arr1) {
// let ret = []
// let toArr = function (arr1) {
// arr1.forEach(function (item) {
// item instanceof Array ? toArr(item) : ret.push(item)
// })
// }
// toArr(arr)
// return ret
// }
// console.log(reduceDimension(arr))
// (3)Array.prototype.flat()
// let arr1 = [1, 2, [3, 4]]
// console.log(arr1.flat()) //[1,2,3,4]
// let arr2 = [1, 2, [3, 4, [5, 6]]]
// console.log(arr2.flat())//[1,2,3,4,5,6]
// let arr3 = [1, 2, [3, 4, [5, 6]]]
// console.log(arr3.flat(Infinity))//[1,2,3,4,[5,6]]
// (4)使用reduce,concat和递归无限反嵌套多层嵌套数组
const arr = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]]
function flat(arr) {
return arr.reduce((calc, cur) => {
return calc.concat(Array.isArray(cur) ? flat(cur) : cur)
}, [])
}
console.log(flat(arr))
</script>