利用apply特性
<script>
let arr = [[1,2],3,[4,5],[6,7],8]
function flat1(arr){
return [].concat.apply([],arr)
}
console.log(flat1(arr)) //[1, 2, 3, 4, 5, 6, 7, 8]
</script>
使用reduce函数
<script>
let arr = [[1,2],3,[4,5],[6,7],8]
function flat1(arr){
return arr.reduce(function(pre,cur){
return pre.concat(cur)
},[])
}
console.log(flat1(arr)) //[1, 2, 3, 4, 5, 6, 7, 8]
</script>
使用ES6解构
<script>
let arr = [[1,2],3,[4,5],[6,7],8]
function flat1(arr){
return [].concat(...arr)
}
console.log(flat1(arr)) //[1, 2, 3, 4, 5, 6, 7, 8]
</script>
PS:上述方法只能作用于二维数组,当出现多维数组时无法解决问题
多维数组解决方法
方法一:
<script>
let arr = [1, 2, [3, 4, [5, 6], 7], 8, 9, [1, 2]]
function flat(arr) {
let arr1 = []
function arrPush(arr){
let len = arr.length
for(let i=0; i< len; i++){
if(arr[i] instanceof Array){
arrPush(arr[i])
}else{
arr1.push(arr[i])
}
}
return arr1
}
return arrPush(arr)
}
console.log(flat(arr))
</script>
方法一:(优化)
<script>
let arr = [1, 2, [3, 4, [5, 6], 7], 8, 9, [1, 2]]
function flat(arr) {
let arr1 = []
function arrPush(arr){
let len = arr.length
for(let i=0; i< len; i++){
arr[i] instanceof Array ? arrPush(arr[i]):arr1.push(arr[i])
}
return arr1
}
return arrPush(arr)
}
console.log(flat(arr)) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
</script>
方法二
<script>
let arr = [1, 2, [3, 4, [5, 6], 7], 8, 9, [1, 2]]
function flat(arr) {
let arr1 = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] instanceof Array) {
arr1 = arr1.concat(flat(arr[i]))
} else {
arr1.push(arr[i])
}
}
return arr1
}
console.log(flat(arr)) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
</script>
方法三
<script>
let arr = [1, 2, [3, 4, [5, 6], 7], 8, 9, [1, 2]]
function flat(arr) {
return arr.reduce(function(pre,cur){
return pre.concat(Array.isArray(cur)?flat(cur):cur)
},[])
}
console.log(flat(arr)) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2]
</script>
网友评论