在处理多数组组合时,可能会经常要拼接成一个数组,今天我们一起聊聊数组的转变
我常用的是第三种 apply 方法
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、用递归实现多维数组转化为一维数组
var list = [
[111,222,3333,444],
[ 555, 666, 777, [123] ],
[ 888 ],
[ 999, 1212 ]
]
function flatten(arr) {
return [].concat(...arr.map(x=>Array.isArray(x) ? flatten(x) : x))
}
var lists = flatten(list)
console.log(lists)
6、针对于简单的多维数组的转化
var list = [
[111,222,3333,444],
[555,666,777,[123]],
[888],
[999,1212]
]
var lists = (list + '').split(',')
console.log(lists.map(Number))
// let oneArr = values?.map((el) => {
// return el.getData.map((item) => {
// return {
// reportId: item.id,
// reportQty: item.editReportQty
// };
// });
// });
// var params = [].concat.apply([], oneArr);
// console.log(params);