zoukankan      html  css  js  c++  java
  • 多维数组降维的几种方法

    这里只说二维数组降低到一维数组的方法,关于三维数组,先用下面这些方法降低到二维,再降低到一维即可

    1.常规循环遍历方法

        var a = [1,2,[3,4]]
        var result = [];
        for(var i=0; i< a.length; i++){
            if(a[i].constructor == Array) {
                for(var j=0; j<a[i].length; j++){
                    result.push(a[i][j])
                }
            }else {
                result.push(a[i])
            }
        }
        console.log(result)// [1,2,3,4]

    2利用contact 

        var a = [1,2,[3,4]]
        var result = []
        for(var i=0; i<a.length; i++){
            if(a[i].constructor == Array) {
                result = result.concat(a[i])
            }else {
                result.push(a[i])
            }
        }
        console.log(result) // [1,2,3,4]

    3.利用扩展运算符

    扩展运算符相当于数组拆成最小单位了,...[1,,2,,[3, 4]] 相当于变成了 1,2,  [3, 4];  这样 [].concat(...a) 就相当于 [].concat(1,2,[3,4])

        var a = [1,2,[3,4]]
        var result = []
        result = [].concat(...a)
        console.log(result) // [1,2,3,4]

    4.利用apply

    这个跟扩展运算符类似,apply 会把数组a 拆分,拆成 1,2,[3, 4] 依次传递给concat方法,  效果就跟 扩展运算符一样了。

       var a = [1,2,[3,4]]
         var result = []
         result = Array.prototype.concat.apply([], a)
         console.log(result) // [1,2,3,4]
  • 相关阅读:
    CF1454F Array Partition
    leetcode1883 准时抵达会议现场的最小跳过休息次数
    leetcode1871 跳跃游戏 VII
    leetcode1872 石子游戏VIII
    CF1355C Count Triangles
    CF1245D Shichikuji and Power Grid
    CF1368C Even Picture
    CF1368D AND, OR and square sum
    CF1395C Boboniu and Bit Operations
    SpringBoot和开发热部署
  • 原文地址:https://www.cnblogs.com/yalong/p/10615194.html
Copyright © 2011-2022 走看看