Array.prototype.flat #
此示例中的数组有多个嵌套级别:它包含一个数组,该数组又包含另一个数组。
const array = [1, [2, [3]]];
// ^^^^^^^^^^^^^ outer array
// ^^^^^^^^ inner array
// ^^^ innermost arrayArray#flat 返回给定数组的扁平化版本。
array.flat();
// → [1, 2, [3]]
// …is equivalent to:
array.flat(1);
// → [1, 2, [3]]默认深度为 1,但您可以传递任何数字以递归地扁平化到该深度。要递归地扁平化直到结果不再包含嵌套数组,我们传递 Infinity。
// Flatten recursively until the array contains no more nested arrays:
array.flat(Infinity);
// → [1, 2, 3]为什么此方法称为 Array.prototype.flat 而不是 Array.prototype.flatten? 阅读我们的 #SmooshGate 写作以了解更多信息!
Array.prototype.flatMap #
这是一个示例。我们有一个 duplicate 函数,它接受一个值,并返回一个包含该值两次的数组。如果我们将 duplicate 应用于数组中的每个值,我们将得到一个嵌套数组。
const duplicate = (x) => [x, x];
[2, 3, 4].map(duplicate);
// → [[2, 2], [3, 3], [4, 4]]然后,您可以对结果调用 flat 来扁平化数组
[2, 3, 4].map(duplicate).flat(); // 🐌
// → [2, 2, 3, 3, 4, 4]由于这种模式在函数式编程中非常常见,因此现在有一个专门的 flatMap 方法来处理它。
[2, 3, 4].flatMap(duplicate); // 🚀
// → [2, 2, 3, 3, 4, 4]与单独执行 map 然后 flat 相比,flatMap 的效率更高。
有兴趣了解 flatMap 的用例吗?查看 Axel Rauschmayer 的解释。
Array#{flat,flatMap} 支持 #
- Chrome: 自版本 69 起支持
- Firefox: 自版本 62 起支持
- Safari: 自版本 12 起支持
- Node.js: 自版本 11 起支持
- Babel: 支持