关于前端:前端面试题-数组扁平化方法总结

38次阅读

共计 1069 个字符,预计需要花费 3 分钟才能阅读完成。

数组扁平化

1. Array.prototype.flat(depth) 办法

2. 转换成字符串

2.1 toString + map + parseInt

var arr = [[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, [12, 13, [14, 15, 16]]], 17],
  str = arr.toString(), // '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17'
  strArr = str.split(','), // ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17']
  res = strArr.map(item => parseInt(item)) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

2.2 toString + JSON.parse

var arr = [[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, [12, 13, [14, 15, 16]]], 17],
  str = arr.toString(), // '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17'
  jsonStr = '[' + str + ']', // '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]'
  res = JSON.parse(jsonStr) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

3. 递归

function flat(array) {
  /* 递归 */
  var _res = [],
    dfs = function (arr) {for (let i = 0; i < arr.length; i++) {Object.prototype.toString.call(arr[i]) === '[object Array]'
          ? dfs(arr[i])
          : _res.push(arr[i])
      }
    }

  dfs(array)

  return _res
}

4. 迭代

function flat(array) {
  /* 迭代 */
  var queue = [array],
    res = [],
    next

  while (queue.length) {next = queue.shift()

    Object.prototype.toString.call(next) === '[object Array]'
      ? Array.prototype.push.apply(queue, next)
      : res.push(next)
  }

  return res
}

正文完
 0