举例说明把一个数组扁平化的方法有哪些?
数组扁平化是将嵌套数组转换为一维数组的过程。以下是几种常见的方法:

### 1. 使用 `Array.prototype.flat()`

ES2019 引入了 `flat()` 方法,可以直接扁平化嵌套数组,指定深度。

```javascript
const nestedArray = [1, [2, [3, 4]], 5];
const flatArray = nestedArray.flat(2); // 深度为 2
console.log(flatArray); // [1, 2, 3, 4, 5]
```

### 2. 使用递归

可以通过递归函数自定义扁平化逻辑,适用于任意深度的嵌套数组。

```javascript
function flatten(array) {
let result = [];
array.forEach(item => {
if (Array.isArray(item)) {
result = result.concat(flatten(item)); // 递归扁平化
} else {
result.push(item);
}
});
return result;
}

const nestedArray = [1, [2, [3, 4]], 5];
const flatArray = flatten(nestedArray);
console.log(flatArray); // [1, 2, 3, 4, 5]
```

### 3. 使用 `reduce`

可以结合 `reduce` 方法来实现扁平化。

```javascript
function flatten(array) {
return array.reduce((acc, item) => {
return acc.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}

const nestedArray = [1, [2, [3, 4]], 5];
const flatArray = flatten(nestedArray);
console.log(fla
展开
评论