1.用迭代或者递归打平数组
ECMAScript在Array.prototype上增加了:两个方法flat(),flatMap()。
在没有这两个方法之前,打平数组就要用迭代或者递归的方法
如下示例:
function flatten(sourceArray, flattenedArray = []){
for (const element of sourceArray) {
if (Array.isArray(element)) {
flatten(element, flattenedArray);
} else {
flattenedArray.push(element);
}
}
return flattenedArray;
}
const arr = [[0], 1, 2, [3, [4, 5]], 6];
console.log(flatten(arr))
//[0, 1, 2, 3, 4, 5, 6]
但可选择打平到第几级就更好了(通过添加参数depth改写)
function flatten(sourceArray, depth, flattenedArray = []){
for (const element of sourceArray) {
if (Array.isArray(element) && depth > 0) {
flatten(element, depth -1, flattenedArray);
} else {
flattenedArray.push(element);
}
}
return flattenedArray;
}
const arr = [[0], 1, 2, [3, [4, 5]], 6];
console.log(flatten(arr,1))
//[0, 1, 2, 3, [4, 5], 6]
2.Array.prototype.flat(depth)打平数组
为了更规范,增加的Array.prototype.flat(depth)就可以实现上述功能
Array.prototype.flat(depth)接受一个depth参数,返回一个要打平Array实例的浅复制本。
const arr = [[0], 1, 2, [3, [4, 5]], 6];
console.log(arr.flat(2));
//[0, 1, 2, 3, 4, 5, 6]
3.Array.prototype.flatMap()打平数组
Array.prototype.flatMap()打平数组会执行一次映射操作,比Array.prototype.flat(depth)高效,浏览器之用执行一次遍历.
flatMap()的函数签名与map相同。例子如下:
const arr = [[1], [3], [5]];
console.log(arr.map([x] => [x, x+1]));
//[[1, 2], [3, 4], [5, 6]]
console.log(arr.flatMap([x] => [x, x+1]));
//[0, 1, 2, 3, [4, 5], 6]