JavaScript 多维数组转一维数组
最新的 ES 规范其实也加入了这个方法,功能是将一个数组压平,比如 [1, 2, [3, [4, 5, [6, [7, 8]]]]]
,会被处理成 [1, 2, 3, 4, 5, 6, 7, 8]
。更进一步,实现可以压平指定深度的数组。
function flatten(list) {
if (list.length === 0) return [];
const head = list[0];
if (head instanceof Array) {
list[0] = flatten(head);
} else {
list[0] = [list[0]];
}
return list[0].concat(flatten(list.slice(1)));
}
function flattenDepth(list, n) {
if (list.length === 0) return [];
if (n === 0) return list;
const head = list[0];
if (head instanceof Array) {
list[0] = flattenDepth(head, n - 1);
} else {
list[0] = [list[0]];
}
return list[0].concat(flattenDepth(list.slice(1), n));
}
// test
const a = flatten([1, 2, [3, [4, 5, [6, [7, 8]]]]]);
console.log(a);
const b = flattenDepth([1, 2, [3, [4, 5, [6, [7, 8]]]]], 2);
console.log(b);
const c = flattenDepth([1, 2, [3, [4, 5, [6, [7, 8]]]]], Number.MAX_VALUE);
console.log(c);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论