js 多维数组变成一维数组

一、所用方法即示例

1.concat

合并两个或多个数组,返回新数组,不会改变原数组

const a = [1,2,3]
const b = [7,4,1]
console.log(a.concat(b))
// [1,2,3,7,4,1]

2.apply

apply方法能劫持另外一个对象的方法, 继承另外一个对象的属性
apply方法能接受两个参数 => Function.apply(obj, args)
obj: 这个对象将代替Function类里this对象
args:这个是数组,它将作为参数传给Function(args–>arguments)

3.例子

let arr = [[1, 2, 3], [4, 5, 6], [7, 4, 1, 8, 5, 2]]
const newArr = [].concat.apply([], arr)
console.log(newArr)
// [1,2,3,4,5,6,7,4,1,8,5,2]

二、封装函数

// arr表示传入的多维数组
// dimension表示数组的维度
// isFirst传入true
const DimensionalityReduction = (arr, dimension, isFirst) => {
    
    
    if (isFirst) {
    
    
        dimension--
    }
    let newArr = [].concat.apply([], arr)  // 对数组进行降维处理
    if (dimension > 1) {
    
    
        dimension--
        DimensionalityReduction(newArr, dimension, false)  // 递归调用
        return
    }
    return newArr  // 返回结果
}

// 测试
const arr = [[1, 2, [3, 1, 2]], [4, 5, 6], [7, 4, 1, 8, 5, 2, [1, 2, 3]]]
console.log(DimensionalityReduction(arr, 3, true)) // [1,2,3,1,2,4,5,6,7,4,1,8,5,2,1,2,3]

猜你喜欢

转载自blog.csdn.net/weixin_45150813/article/details/121177823