在处理多数组组合时,经常要拼接成一个数组,今天我们一起聊聊数组的转变,主要聊聊二维变一维吧
1、用es5的
reduce
和concat
组合
var list = [
[111,222,3333,444],
[555,666,777],
[888],
[999,1213]
]
var lists = list.reduce((a,b) => a.concat(b))
console.log(lists)
2、用ES6的flat扁平处理
var list = [
[111,222,3333,444],
[555,666,777],
[888],
[999,1213]
]
var lists = list.flat()
console.log(lists)
3、用
apply
实现
var list = [
[111,222,3333,444],
[555,666,777],
[888],
[999,1213]
]
var lists = [].concat.apply([],list)
console.log(lists)
4、用
call
实现
var list = [
[111,222,3333,444],
[555,666,777],
[888],
[999,1213]
]
var lists = [].concat.call([],...list)
console.log(lists)
5、用递归实现多维数组转化为一维数组
6、针对于简单的多维数组的转化
var list = [
[111,222,3333,444],
[555,666,777,[123]],
[888],
[999,1212]
]
var lists = (list + '').split(',')
console.log(lists.map(Number))