美文网首页
数组层级展开,多维数组拍平

数组层级展开,多维数组拍平

作者: 前端青音 | 来源:发表于2019-10-12 18:22 被阅读0次
methods: {
    openArr(arr) {
      // 方法一:
      let result = []
      arr.map(item => {
        item instanceof Array
          ? (result = result.concat(this.openArr(item)))
          : result.push(item)
      })
      return result
    }
  },
  mounted() {
    console.log(
      'result:',
      this.openArr([
        [1, 2, 2],
        [3, 4, 5, 5],
        [6, 7, 8, 9, [11, 12, [12, 13, [14]]]],
        10
      ])
    )
  }
image.png
methods: {
    openArr(arr) {
      // 方法二
      console.log('openArr:', arr, arr.toString(), arr.toString().split(','))
      return arr
        .toString()
        .split(',')
        .map(val => +val)
    }
  },
  mounted() {
    console.log(
      'result:',
      this.openArr([
        [1, 2, 2],
        [3, 4, 5, 5],
        [6, 7, 8, 9, [11, 12, [12, 13, [14]]]],
        10
      ])
    )
  }
image.png
methods: {
    // 方法三
    openArr(arr) {
      console.log('openArr:', arr)
      return arr.reduce((result, item) => {
        return Array.isArray(item)
          ? [...result, ...this.openArr(item)]
          : [...result, item]
      }, [])
    }
  },
  mounted() {
    console.log(
      'result:',
      this.openArr([
        [1, 2, 2],
        [3, 4, 5, 5],
        [6, 7, 8, 9, [11, 12, [12, 13, [14]]]],
        10
      ])
    )
  }

运行结果:


image.png

相关文章

网友评论

      本文标题:数组层级展开,多维数组拍平

      本文链接:https://www.haomeiwen.com/subject/kolhyctx.html