数组扁平化
作者:互联网
数组扁平化
数组扁平化是指将一个多维数组变为一维数组
[1, 2, [3, 4, [5, 6], 7], 8, 9] > [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法
<script>
let arr = [1, 2, [3, 4, [5, 6], 7], 8, 9]
function fn1(data) {
let arr1 = []
if (Array.isArray(data)) {
for (let index = 0; index < data.length; index++) {
if (Array.isArray(data[index])) {
arr1 = arr1.concat(fn1(data[index]))
} else {
console.log(data[index]);
arr1.push(data[index])
}
}
}
return arr1
}
let arr2 = fn1(arr)
console.log(3, ":", arr2);
</script>
标签:index,扁平化,fn1,let,数组,arr1,data 来源: https://blog.csdn.net/weixin_52310078/article/details/116298434